问题描述
有一个被普遍接受的方式来避免使用对WCF服务KnownType属性?我一直在做一些研究,它看起来像有两种选择:
- 的
- 的
我不是一个大风扇不必添加静态属性KnownType我每次添加一个新类型的时候,因此希望避免的。
是否有应使用第三种选择?如果是这样,是什么呢?如果不是这样,它的上面两个选项是正确的方式去
修改 - 使用方法
第三个选项是使用反射
[DataContract]
[KnownType( DerivedTypes)]
公共抽象类FooBase
{
私有静态类型[] DerivedTypes()
{
返回的typeof(FooBase).GetDerivedTypes(Assembly.GetExecutingAssembly ())ToArray的();
}
}
我想发布的东西似乎是我能想到的迄今为止最简单,最优雅的解决方案。如果另一个答案走来那最好不过,我也有去。但现在,这个工作很好。
的基类,仅有的有一个的 KnownType
属性,指着一个名为 DerivedTypes()方法
:
[ KnownType(DerivedTypes)]
[DataContract]
公共抽象类TaskBase:EntityBase
{
//其他类成员在这里
私有静态类型[] DerivedTypes()
{
返回的typeof(TaskBase).GetDerivedTypes(Assembly.GetExecutingAssembly())ToArray的()。
}
}
的
GetDerivedTypes()
方法,在一个单独的ReflectionUtility类:
公共静态的IEnumerable<类型> GetDerivedTypes(这种类型的基本类型,装配装配)
{
变种类型=从assembly.GetTypes吨()
,其中t.IsSubclassOf(基本类型)
选择吨;
返回类型;
}
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:
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();
}
}
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;
}
这篇关于普遍接受的方式,以避免为每个派生类KnownType属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!