我正在使用 C# 和 WCF 来做 Web 服务。我有一个实现 IEnumerable 的类的成员变量。我尝试通过执行以下操作将其序列化为我的数据合同的一部分:
[DataContract]
class Item
{
[DataMember]
private IEnumerable<KeyValuePair<string, object>> Member1
{
get { return this._Properties; }
set { this._Properties = Value; }
}
}
其中 _Properties 的类型为:
class PropertiesCollection:IEnumerable<KeyValuePair<string, object>>
{
...
}
我认为 WCF 会将 Member1 序列化为 IEnumerable,因为这是我赋予该成员的类型,但我收到 InvalidDataContractExceptiom,并显示以下消息:
PropertyCollection 类型无法序列化。请考虑使用 DataContractAttribute 属性标记它,并使用 DataMemberAttribute 属性标记要序列化的所有成员。如果类型是集合,请考虑使用 CollectionDataContractAttribute 对其进行标记。有关其他支持的类型,请参阅 Microsoft .NET Framework 文档。
WCF 似乎正在查看通过 Member1 (PropertyCollection) 传递的对象的运行时类型,而不是属性的类型 (IEnumenable)。这种理解正确吗?将 [CollectionDataContract] 添加到 PropertiesCollection 是唯一的修复吗?如果可能的话,我更愿意让服务合同不特定(即它只知道 iot 是 IEnumerable)。
我突然想到:我认为你需要装饰一下Member1
具有 KnownType 属性的属性。
see: http://msdn.microsoft.com/en-us/library/ms730167.aspx http://msdn.microsoft.com/en-us/library/ms730167.aspx
[DataContract]
[KnownType(typeof(PropertiesCollection))] //<--- this guy here
class Item
{
[DataMember]
private IEnumerable<KeyValuePair<string, object>> Member1
{
get { return this._Properties; }
set { this._Properties = Value; }
}
}
添加上面链接中的示例 2 中的代码,以显示即使该属性是类装饰器,它也如何应用于 DataMember:
public interface ICustomerInfo {}
[DataContract(Name = "Customer")]
public class CustomerTypeA : ICustomerInfo {}
[DataContract(Name = "Customer")]
public class CustomerTypeB : ICustomerInfo {}
[DataContract]
[KnownType(typeof(CustomerTypeB))] //<-- check it! This applies to 'buyer'
public class PurchaseOrder
{
[DataMember]
ICustomerInfo buyer;
[DataMember]
int amount;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)