DataContract Serialize abstract class

前端 未结 1 1829
野性不改
野性不改 2021-02-09 17:51

I have an interface IServiceInfo and an abstract class ServiceInfo. There are several classes inherited from ServiceInfo, like CoreServiceInfo, ModuleServiceInfo etc. There is a

相关标签:
1条回答
  • 2021-02-09 18:42

    Get all the types in all loaded assemblies that implement given abstract class or interface(ref:Implementations of interface through Reflection)

     var allTypes =  AppDomain
                .CurrentDomain
                .GetAssemblies()
                .SelectMany(assembly => assembly.GetTypes())
                .Where(type => typeof(A).IsAssignableFrom(type));
    

    Then create serializer passing allTypes as known types parameter, as below

    var serializer = new DataContractSerializer(typeof(A), allTypes);
    

    that's it - you will be able to serialize and deserialize any type that derives from A (A could be class or interface, if interface, serializer writes elements as deriving from xs:anyType.

    0 讨论(0)
提交回复
热议问题