问题
C# 7.2 introduced ref struct
s. However, given a ref struct
like this:
public ref struct Foo {
public int Bar;
}
I cannot use it as a type argument:
int i = 0;
var x = Unsafe.As<int, Foo>(ref i); // <- Error CS0306 The type 'Foo' may not be used as a type argument.
I understand that ref structs can only exist on the stack, and not the heap. But what if the generic method that would use such ref structs is guaranteed to never put them on the heap, as in the example above that uses System.Runtime.CompilerServices.Unsafe
package? Why can I not use them in those cases as type parameters?
来源:https://stackoverflow.com/questions/50871135/why-ref-structs-cannot-be-used-as-type-arguments