WCF:序列化为数组的通用列表

所以我正在使用WCF和我的服务返回包含通用列表的类型。 WCF目前正通过线路将这些转换为arrays。 有没有办法配置WCF以后再将它们转换回列表? 我知道在添加服务引用时单击高级有一种方法,但我正在寻找配置文件或类似的解决方案。

[DataContract(IsReference = true)] public class SampleObject { [DataMember] public long ID { get; private set; } [DataMember] public ICollection Objects { get; set; } } 

这也很奇怪,因为一个服务将其作为列表返回,另一个服务作为数组返回,我很确定它们的配置相同。

在此处输入图像描述

在添加服务引用时的高级选项卡上,您也可以设置此选项。 标准数组已设置。

我认为这完全取决于客户端工具从WSDL生成合同的方式。 在我的例子中,我创建了一个包含我的[OperationContract]和[DataContract]类的可重用.dll,并从客户端和服务器中使用它,而不是使用SvcUtil生成一个。 这样我保留了我的generics列表。

另外,请注意不要在使用WCF序列化实例的类中同时使用数组和generics,因为在反序列化过程中会出现问题:所有内容都将转换为ArrayOf(如果不更改配置) )或收集类型。

因此,您将在反序列化期间从WCF代码中获取错误,尝试在等待集合的位置分配数组,反之亦然。

这只是我在WCF小项目中学到的2分建议。 🙂

我找到了一个更简单且适用于我的解决方案,尽管它可能对其他人不起作用。 我只是从使用ICollection(IList也生成此结果)切换到List。 之后它运作良好。

从这里解决。

我还从底部附近发现了一个可能的配置解决方案。

    

而不是在数据协定中使用ICollection ,它将在客户端应用程序中作为AnotherObject[]

试试这个:

定义新的数据合同

 [CollectionDataContract] public class AnotherObjectCollection : List {} 

在你的代码中:

 DataContract(IsReference = true)] public class SampleObject { [DataMember] public long ID { get; private set; } [DataMember] public AnotherObjectCollection Objects { get; set; } } 

在Visual Studio中(与svcUtil相同),客户端代理代码将如下所示:

 [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")] [System.Runtime.Serialization.CollectionDataContractAttribute(Name="AnotherObjectCollection", Namespace="http://schemas.datacontract.org/2004/07/SampleObject", ItemName="AnotherObject")] [System.SerializableAttribute()] public class AnotherObjectCollection : System.Collections.Generic.List {} DataContract(IsReference = true)] public class SampleObject { [DataMember] public long ID { get; private set; } [DataMember] public AnotherObjectCollection Objects { get; set; } } 

这也适用于内置的.NET类型。

安东尼奥