c# - 为什么 VS 警告我 typeof(T) 永远不是泛型方法中提供的类型,其中类型参数仅限于实现 T?

标签 c# visual-studio generics type-parameter

我希望问题是正确的,所以让我们举个例子。想象以下通用方法:

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)

但这有不同的含义。
只有 TBase 时,第一个语句(使用 typeof(Base))才为 true。对于从 Base 派生的任何类型,它将是 false
第二条语句(variableOfTypeT is Base)在您的类中始终为true,因为从Base 派生的任何类都将返回true 以检查其基类。

关于c# - 为什么 VS 警告我 typeof(T) 永远不是泛型方法中提供的类型,其中类型参数仅限于实现 T?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14854662/

相关文章:

c# - 您将如何使用 LINQ 编写此映射过滤器链?

Java 泛型 : method is not applicable for the arguments (T)

c# - Application Insights - ILogger 参数呈现为自定义维度中的对象名称

c# - 动态对象的特殊字符?

visual-studio - 为什么 Visual Studio 2013 非常慢?

visual-studio - VS Express 还是 VS :WebDev Express include XSLT debugging

c++ - 如何将 istream 与字符串一起使用

java - 比较方法和泛型

java - 如何将 Java 反射与通用参数一起使用

c# - 从 MS-Word ApplicationClass 获取 PID?