[KnownType("DerivedTypes")] [DataContract] public abstract class TaskBase { // other class members here private static Type[] DerivedTypes() { return typeof(TaskBase).GetDerivedTypes(Assembly.GetExecutingAssembly()).ToArray(); } }
用于反射实现KnowType而不用全部标记。无论是参数还是作为结果返回还是作为其中的一个成员都要继承此类
public static IEnumerable<Type> GetDerivedTypes(this Type baseType, Assembly assembly) { var types = from t in assembly.GetTypes() where t.IsSubclassOf(baseType) select t; return types; }
这是上一个代码块中引用的GetDerivedTypes的方法实现
将TaskBase作为base类继承到序列化的类中,比如我有类Foo:
[DataContract] public class Foo { [DataMember] public object Hello {get;set;} }
[DataContract] public class Bar { [DataMember] public long Id {get;set;} }
如果仅仅是Bar被序列化传递,那么Bar集成于TaskBase就可以了,如果是
Foo的Hello成员是Bar类的话,那么两个类都要继承,即:
[DataContract] public class Foo:TaskBase { [DataMember] public object Hello {get;set;} } [DataContract] public class Bar:TaskBase { [DataMember] public long Id {get;set;} }