简体   繁体   English

使用接口而不是具体类型IEnumerable会导致异常

[英]using interface and not concrete type IEnumerable cause an exception

It is better to work with interfaces and not with concrate type so our application will have modularity and freedom to use any desired type (as long it implements the interface); 最好是使用接口而不是简洁的类型,因此我们的应用程序将具有模块化和自由使用任何期望的类型(只要实现了接口)。

So in my Worker object I created a member called CarNumbers in type IEnumerable: 因此,在我的Worker对象中,我创建了一个名为IEnumerable类型的CarNumbers成员:

[DataContract(Namespace = "", Name = "Worker")]
public class Worker {
    ....
    ....
    [DataMember(IsRequired = false, Name = "CarNumbers")]
    public IEnumerable<string> CarNumbers  { get; set; }
    ....
}

Now I am trying to serialize Worker object into XML and I get the exception: 现在,我尝试将Worker对象序列化为XML,但出现异常:

Cannot serialize member Worker.CarNumbers of type System.Collections.Generic.IEnumerable`1[[string]] because it is an interface. 无法序列化类型为System.Collections.Generic.IEnumerable`1 [[string]]的成员Worker.CarNumbers,因为它是接口。

How can I solve this exception without breaking the indepenedecy and using concrate type? 如何在不破坏独立性和使用精确类型的情况下解决此异常?

It depends on the serializer. 这取决于串行器。 In general, serialization needs to be able to create concrete types (otherwise, when deserializing how would it know what to actually create? You can't create an instance of just an interface...) so you have to leak some of the abstraction somewhere. 通常,序列化需要能够创建具体的类型(否则,在反序列化时它将如何知道实际要创建什么?您不能仅创建接口的实例...),因此必须泄漏一些抽象某处。

That all said, using the NetDataContractSerializer lets you do what you want from a code perspective, though all it does is persist the concrete types necessary in the serialized output. 综上所述 ,使用NetDataContractSerializer可以从代码角度执行所需的操作,尽管它所做的只是在序列化输出中保留必要的具体类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM