Why ref structs cannot be used as type arguments?

随声附和 提交于 2020-05-25 06:40:42

问题


C# 7.2 introduced ref structs. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!