考虑以下类型:
-
(int, int)
→ 管理。 -
struct MyStruct { public (int,int) Value; }
→ 不受管理!
问题: 非泛型结构 MyStruct
,它有一个管理成员 (int,int)
已被评估为托管类型。
预期行为:包含托管成员的结构应被视为托管,与 struct MyStruct { int? Value; }
相同被认为是托管的。
示例 1 - 非托管约束
class Program
{
static void DoSomething<T>() where T : unmanaged { }
struct MyStruct { public (int, int) Value; }
static void Main(string[] args)
{
DoSomething<MyStruct>(); // → OK
DoSomething<(int, int)>(); // → Shows compile-time error
}
}
Error CS8377 The type '(int, int)' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Program.DoSomething()'
示例 2 - 指针或 sizeof
使用上述结构,行为与 pointers 相同或 sizeof
运算符(operator):
unsafe
{
(int, int)* p1; // → Compile-time error,
MyStruct* p2; // → Compiles
}
Error CS0208 Cannot take the address of, get the size of, or declare a pointer to a managed type('(int, int)')
问题
包含
ValueTuple
的结构如何实现?被视为unmanaged
并能满足unmanaged
ValueTuple
时的约束被视为托管?结构如何具有
ValueTupple<T1, T2>
和一个包含Nullable<T>
的结构区别对待?
注意 1: IMO 问题不同于 Proposal: Unmanaged constructed types (DavidG 在评论中提到),因为 MyStruct
不是通用的,另一方面,int?
和 (int,int)
两者都是管理的,但是 struct MyStruct { int? Value; }
和 struct MyStruct { (int, int) Value; }
评价不同。
最佳答案
感谢您的报告。这只是编译器中的一个错误。用作字段的元组应注册为通用类型,因此在 非托管类型
中无效。它似乎正在评估为一个 tulpe 而错过了这个检查。
好消息是,在 C# 8.0 中,此限制将消失。 (int, int)
类型是有效的非托管类型
。
关于c# - 为什么包含 ValueTuple 的结构可以满足非托管约束,而 ValueTuple 本身却不能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53992855/