我希望问题是正确的,所以让我们举个例子。想象以下通用方法:
public abstract class Base : IDisposable
{
public static IEnumerable<T> GetList<T>()
where T : Base
{
// To ensure T inherits from Base.
if (typeof(T) is Base)
throw new NotSupportedException();
// ...
}
}
根据MSDN关键字 where
将类型参数 T
限制为 Base
类型或从此类继承。
[...] a where clause can include a base class constraint, which states that a type must have the specified class as a base class (or be that class itself) in order to be used as a type argument for that generic type.
此代码也可以编译:
public static T GetFirst()
where T : Base
{
// Call GetList explicitly using Base as type parameter.
return (T)GetList<Base>().First();
}
所以当遵循最后一个代码时 typeof(T)
应该返回 Base
,不是吗?为什么 Visual Studio 然后向我打印此警告?
warning CS0184: The given expression is never of the provided ('Demo.Base') type.
最佳答案
typeof(whatever)
总是返回 Type
类型的实例。 Type
不是从 Base
派生的。
你要的是这个:
if(typeof(T) == typeof(Base))
throw new NotSupportedException("Please specify a type derived from Base");
看起来是一样的是这样的:
if(variableOfTypeT is Base)
但这有不同的含义。
只有 T
是 Base
时,第一个语句(使用 typeof(Base)
)才为 true
。对于从 Base
派生的任何类型,它将是 false
。
第二条语句(variableOfTypeT is Base
)在您的类中始终为true
,因为从Base
派生的任何类都将返回true
以检查其基类。
关于c# - 为什么 VS 警告我 typeof(T) 永远不是泛型方法中提供的类型,其中类型参数仅限于实现 T?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14854662/