“Type not expected”, using DataContractSerializer - but it's just a simple class, no funny stuff?

前端 未结 7 1572
慢半拍i
慢半拍i 2020-11-30 11:10

I\'m refactoring my XML-serialization, and figured I\'d try the DataContractSerializer. Everything runs smoothly, until it needs to serialize this class:

         


        
7条回答
  •  醉话见心
    2020-11-30 11:10

    You can also combine [KnownType] and reflection to make your code more resistant to future changes.

    [DataContract]
    [KnownType("GetKnownPersonTypes")]
    internal class Person
    {
        private static IEnumerable _personTypes;
    
        private static IEnumerable GetKnownTypes()
        {
            if (_personTypes == null)
                _personTypes = Assembly.GetExecutingAssembly()
                                        .GetTypes()
                                        .Where(t => typeof (Person).IsAssignableFrom(t))
                                        .ToList();
            return _personTypes;
        }
    }
    

    Now a DataContractSerializer / DataContractJsonSerializer / XmlSerializer configured to work with Person, will also work with any type derived from Person (as long as it's declared within the same assembly).

提交回复
热议问题