开发者

using interface and not concrete type IEnumerable cause an exception

开发者 https://www.devze.com 2023-04-11 19:01 出处:网络
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);

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 obj开发者_StackOverflowect 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号