【发布时间】:2018-11-25 00:53:16
【问题描述】:
C# 7.2 introducedref structs。但是,给定一个像这样的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 包的示例一样,该怎么办?为什么我不能在这些情况下将它们用作类型参数?
【问题讨论】:
-
泛型方法在另一个程序集中。它可能会做很多你不能用 ref structs 做的事情。在整个程序分析之外,编译器无法验证您所说的方法是否得到保证。我猜这样的分析被认为是禁止的,因为它不能安全地完成,所以它是不允许的。
标签: c# c#-7.2 ref-struct