How/why does XmlSerializer treat a class differently when it implements IList?

后端 未结 2 1627
别跟我提以往
别跟我提以往 2020-12-21 21:27

XmlSerializer is calling IList.Add() on my class and I don\'t understand why.

I have a custom class (one of several classes in a h

2条回答
  •  自闭症患者
    2020-12-21 22:04

    Without a good, minimal, complete code example that reliably reproduces the problem, it will be impossible to provide any specific answer.

    In lieu of that, here are some non-specific notes that may help you:

    1. .NET serialization treats collection types differently from other types. By default, a type that implements any IEnumerable interface (e.g. IList) is considered a collection. Such types are serialized by enumerating the collection and storing the individual elements. On deserialization, .NET assumes it can use an Add() method to populate the deserialized object. Woe unto any type that throws an exception from the Add() method or, worse, doesn't implement one at all.
    2. In some cases, it may be appropriate to mark your type with the [DataContract] attribute. This overrides the default behavior, allowing your type to be treated as a non-collection type.
    3. In other cases, you really should not have implemented IList in the first place, but instead should have exposed the enumeration of elements differently, e.g. as a property that returns the enumeration. Lacking a good code example (well, any code example) it's not possible to say whether this is true in your scenario or not, but I'd say there's at least a 50/50 chance it is.

提交回复
热议问题