Why ref structs cannot be used as type arguments?

前端 未结 1 1097
你的背包
你的背包 2021-02-13 08:54

C# 7.2 introduced ref structs. However, given a ref struct like this:

public ref struct Foo {
  public int Bar;
}

I can

相关标签:
1条回答
  • 2021-02-13 09:38

    One can not use reference structures as type parameters because they cannot escape to a heap. There is no mechanism to tell the compiler that a method promises never to abuse the reference structure.

    Beginning with C# 7.2, you can use the ref modifier in the declaration of a structure type. Instances of a ref struct type are allocated on the stack and can't escape to the managed heap. To ensure that, the compiler limits the usage of ref struct types as follows:

    • A ref struct can't be the element type of an array.
    • A ref struct can't be a declared type of a field of a class or a non-ref struct.
    • A ref struct can't implement interfaces.
    • A ref struct can't be boxed to System.ValueType or System.Object.
    • A ref struct can't be a type argument.
    • A ref struct variable can't be captured by a lambda expression or a local function.
    • A ref struct variable can't be used in an async method. However, you can use ref struct variables in synchronous methods, for example, in those that return Task or Task.
    • A ref struct variable can't be used in iterators.

    More details from Microsoft about ref structs

    0 讨论(0)
提交回复
热议问题