Geo*_*ett 8 c# generics inheritance
考虑以下课程:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我已经将TBase泛型类参数限制为一个类:where TBase : class
我还将TDerived泛型方法参数限制为TBase或从中派生出来的东西:where TDerived : TBase.
我在线上收到错误as TDerived:
类型参数'TDerived'不能与'as'运算符一起使用,因为它没有类类型约束,也没有'class'约束
我明白为了防止错误我需要添加约束class,所以我得到:
where TDerived : class, TBase
Run Code Online (Sandbox Code Playgroud)
当TBase已经被限制为一个类并且TDerived被限制为一个类TBase或从它派生时,为什么我必须这样做?
更新:这个问题是我的博客2011年9月19日的主题.谢谢你这个好问题!
当TBase已被限制为类并且TDerived被限制为TBase或从中衍生时,为什么我必须这样做?
因为值类型可以从引用类型派生.int源自引用类型object,System.ValueType并实现了许多接口.这不是int一个参考类型.
调用SomeMethod<int>一个实例是完全合法的,DerivedClassPool<object>因为int是从对象派生的.
现在,在这里你的批评是必要的情况下.可以构造这样的情况,其中两个类型参数以这样的方式相关,即它们在逻辑上都只能是引用类型,但是其中只有一个被语言分类为"已知为引用类型".
作为读者的练习:你能找到一个吗?可能有必要仔细阅读规范的第10.1.5节,以获得"已知为参考类型"的精确定义.