gpt4 book ai didi

c# - 为什么 ref 结构不能用作类型参数?

转载 作者:行者123 更新时间:2023-12-04 11:19:20 25 4
gpt4 key购买 nike

C# 7.2 introduced ref struct s。然而,给定一个 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 的示例中那样怎么办?包裹?为什么我不能在这些情况下将它们用作类型参数?

最佳答案

不能使用引用结构作为类型参数,因为它们不能转义到堆中。没有机制告诉编译器一个方法 promise 永远不会滥用引用结构。

Beginning with C# 7.2, you can use the ref modifier in the declarationof a structure type. Instances of a ref struct type are allocated onthe stack and can't escape to the managed heap. To ensure that, thecompiler 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

关于c# - 为什么 ref 结构不能用作类型参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50871135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com