请看这段代码:
它编译失败并显示错误消息:
“MyClass”的参数“T”必须为非空值类型,并且在嵌套的任何级别上所有字段也必须为非空值类型,才能将其用作泛型类型或方法的参数。”
然而,
为什么?
namespace ConsoleApp
{
public struct MyPoorGenericStructThatCannotBeUnmanaged<T> where T: unmanaged
{
public T Field;
}
public class MyClass<T> where T: unmanaged
{
}
class Program
{
static void Main()
{
// The type 'MyPoorGenericStructThatCannotBeUnmanaged<int>' must be a non-nullable value type,
// along with all fields at any level of nesting,
// in order to use it as parameter 'T' in the generic type or method 'MyClass<T>'
var obj = new MyClass<MyPoorGenericStructThatCannotBeUnmanaged<int>>();
}
}
}
它编译失败并显示错误消息:
“MyClass”的参数“T”必须为非空值类型,并且在嵌套的任何级别上所有字段也必须为非空值类型,才能将其用作泛型类型或方法的参数。”
然而,
MyPoorGenericStructThatCannotBeUnmanaged<int>
是一个非空值类型,它嵌套的任何级别上的所有字段都是非空值类型。这是通过泛型类型约束where T:unmanaged
来确保的。为什么?