【发布时间】:2011-05-07 15:59:42
【问题描述】:
我正在使用 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)。
【问题讨论】: