Generally accepted way to avoid KnownType attribute for every derived class

前端 未结 6 1404
情书的邮戳
情书的邮戳 2020-12-14 17:19

Is there a generally accepted way to avoid having to use KnownType attributes on WCF services? I\'ve been doing some research, and it looks like there are two options:

6条回答
  •  既然无缘
    2020-12-14 18:04

    The method mentioned by Bob will work as long as all involved classes are in the same assembly.

    The following method will work across assemblies:

    [DataContract]
    [KnownType("GetDerivedTypes")]
    public class BaseClass
    {
      public static List DerivedTypes = new List();
    
      private static IEnumerable GetDerivedTypes()
      {
        return DerivedTypes;
      }
    }
    
    
    [DataContract]
    public class DerivedClass : BaseClass
    {
      //static constructor
      static DerivedClass()
      {
        BaseClass.DerivedTypes.Add(typeof(DerivedClass)); 
      }
    }
    

提交回复
热议问题