C# 泛型类型约束

标签 c# generics

这不应该是有效的 C# 代码吗?

class A<T> where T : class {

    public void DoWork<K>() where K : T {

        var b = new B<K>(); // <- compile time error
    }
}

class B<U> where U : class {

}

编译器吐出这个错误:

error CS0452: The type 'K' must be a reference type in order to use it as parameter 'U' in the generic type or method 'ConsoleApplication1.B'

编译器难道不应该能够弄清楚 K 是类型 T 的约束还是从 T 派生的,所以它显然应该是引用类型(T 被约束为引用类型)?

最佳答案

我之前的回答不正确;我已经删除了它。感谢指出我错误的用户配置器。

Shouldn't the compiler be able to figure out that K is constraint to be of type T or derived from T so it should obviously be a reference type (T is constrained to be a reference type)?

没有。

K 被限制为类型 T 或派生自 T 的类型。T 被限制为引用类型。 这并不意味着K是引用类型。即:object是引用类型,int是从object派生的类型。如果 T 是对象,那么 K 可以是 int,它不是引用类型。

关于C# 泛型类型约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5041967/

相关文章:

c# - 使用 HttpClient 发布自定义类型

c# - 从代码在存储过程中将数据类型 nvarchar 转换为 datetime 时出错

c# - 重用内存流

ios - Swift 中的闭包数组

c# - .net 上的 PDF 查看器

c# - 设置 ItemsSource 后使 ListBox 不选择第一项

java - 是否可以在 Java 中使用原始类型(int)作为泛型类型?

c# - 如何在 C# 中存储返回的 List<T>?

swift - 通用 View 生成器无法快速推断类型

swift - nil 不能转换为 hashable。