Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

c# - Generally accepted way to avoid KnownType attribute for every derived class

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:

  1. Data contract resolver
  2. NetDataContractSerializer

I'm not a big fan of having to statically add KnownType attributes every time I add a new type, hence wanting to avoid it.

Is there a third option that should be used? If so, what is it? If not, which of the above two options are the right way to go?

Edit - use a method

A third option would be to use reflection

[DataContract]
[KnownType("DerivedTypes")]
public abstract class FooBase
{
    private static Type[] DerivedTypes()
    {
        return typeof(FooBase).GetDerivedTypes(Assembly.GetExecutingAssembly()).ToArray();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I wanted to post what seems to be the simplest, most elegant solution that I can think of so far. If another answer comes along that's better, I'll go with that. But for now, this worked well.

The base class, with only one KnownType attribute, pointing to a method called DerivedTypes():

[KnownType("DerivedTypes")]
[DataContract]
public abstract class TaskBase : EntityBase
{
    // other class members here

    private static Type[] DerivedTypes()
    {
        return typeof(TaskBase).GetDerivedTypes(Assembly.GetExecutingAssembly()).ToArray();
    }
}

The GetDerivedTypes() method, in a separate ReflectionUtility class:

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...