考虑下面的类:类和方法层面的泛型类型约束作用
public class DerivedClassPool<TBase> where TBase : class
{
public TBase Get(Type componentType)
{
// Not important, but you get the idea
return Activator.CreateInstance(componentType) as TBase;
}
public TDerived SomeMethod<TDerived>() where TDerived : TBase
{
return Get(typeof(TBase)) as TDerived;
}
}
注意我已经限制了TBase
泛型类的说法应是一个类:where TBase : class
我也制约了TDerived
通用方法的参数是TBase
或从中衍生出来的东西:where TDerived : TBase
。
我上as TDerived
行错误:
类型参数“TDerived”不能使用的“为”经营者,因为它没有一个类类型约束,也不是一个“类”约束
我明白,为了防止我需要添加约束class
的错误,所以我会得到:
where TDerived : class, TBase
为什么我必须这样做,当TBase
已被限制为一个类和TDerived
被约束为TBase
或从它派生?
请参阅http://stackoverflow.com/questions/8002148/c-sharp-generics-contraints-propagation。埃里克把它放在那里。 – 2012-01-17 16:56:19
@Jason,我认为用'but'读得更好。 – Joey 2012-01-17 16:57:20
@Joey:够公平的。我只是讨厌以'but'开头的句子,尽管现在使用连词开始的句子被认为是正确的。我责怪我的高中英语老师。他是经典英语惯例的守护者。 – 2012-01-17 17:40:52