问题
I have an interface IServiceInfo and an abstract class ServiceInfo. There are several classes inherited from ServiceInfo, like CoreServiceInfo, ModuleServiceInfo etc. There is a service contract named RootService which returns IServiceInfo.
public IServiceInfo GetServiceInfo()
{
return (IServiceInfo)new CoreServiceInfo();
}
I am having problem serializing. I can use ServiceKnownType to identify base class, and KnownType to identify child class.
Problem is I do not know all the ServiceInfo child, since application can have plugins with different child inherited from ServiceInfo, so I cannot tell serializer to have all the child in serialized XML.
I can ignore abstract class, but it contains certain common implementation so I need to keep it. As a work around I can have another class say "sampleServiceInfo" and convert all the info classes to sampleServiceInfo and return it from Service method, and define KnownType to ServiceInfo class.
[KnownType(typeof(sampleServiceInfo))]
public class ServiceInfo : IServiceInfo
But that does not sound pretty way to do it. Please suggest. Do I need to write custom serializer? Is there any way to serialize base only and ignoring the child when both has same members?
回答1:
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.
来源:https://stackoverflow.com/questions/4495887/datacontract-serialize-abstract-class