简体   繁体   中英

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:

[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:

Cannot serialize member Worker.CarNumbers of type System.Collections.Generic.IEnumerable`1[[string]] because it is an interface.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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