XmlSerializer: “The type 'Type' may not be used in this context”

后端 未结 3 1942
無奈伤痛
無奈伤痛 2021-01-03 03:29

I\'m trying to figure out how to serialize any class using the XmlSerializer, without using the XmlInclude attribute. Generally works, but with the followi

相关标签:
3条回答
  • 2021-01-03 04:08

    The serialization side is easy - instead of using typeof(ReactObject) when getting the serializer, use list.GetType(), which will return AList rather than ReactObject and create the correct serializer. If you are worried about instantiating too many serializers you can always keep them in a dictionary keyed by type.

    Deserialization is harder as you have to know the type of object first - if you can't get the caller to tell you what type to expect, you will need to read the data before you try deserializing to determine the type.

    0 讨论(0)
  • 2021-01-03 04:15

    Does ReactListObject inherit from ReactObject? ser1 is instantiated to serialize types of ReactObject, but from your code sample I can only tell that list is of type ReactListObject.

    0 讨论(0)
  • 2021-01-03 04:25

    First of all should not it be like this:

    //[XmlInclude(typeof(B))]
    [Serializable]
    public class A : ReactListObject
    {
        public int AValue = 1;
    }
    
    [XmlInclude(typeof(A))]
    public class B : A
    {
        public int BValue = 2;
    }
    
    0 讨论(0)
提交回复
热议问题