C# 7.2 引入了 ref struct
。 然而,如果有一个像这样的ref struct
:
public ref struct Foo {
public int Bar;
}
我无法将其用作类型参数:
int i = 0;
var x = Unsafe.As<int, Foo>(ref i); // <- Error CS0306 The type 'Foo' may not be used as a type argument.
我明白ref结构体只能存在于堆栈中,而不能存在于堆中。但是如果使用这样的ref结构体的泛型方法保证永远不会将它们放置在堆中,例如上面使用了System.Runtime.CompilerServices.Unsafe
包的示例,为什么不能在这些情况下将它们用作类型参数呢?