c# - 为什么包含 ValueTuple 的结构可以满足非托管约束,而 ValueTuple 本身却不能?

标签 c# .net generics unmanaged c#-7.3

考虑以下类型:

  • (int, int) → 管理。
  • struct MyStruct { public (int,int) Value; } → 不受管理!

问题: 非泛型结构 MyStruct ,它有一个管理成员 (int,int)已被评估为托管类型。

预期行为:包含托管成员的结构应被视为托管,与 struct MyStruct { int? Value; } 相同被认为是托管的。

这两种类型的行为似乎都违反了文档 [1][2] .

示例 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)')

问题

  1. 包含 ValueTuple 的结构如何实现?被视为 unmanaged并能满足unmanaged ValueTuple 时的约束被视为托管?

  2. 结构如何具有 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/

相关文章:

c# - NodaTime TypeInitializationException 仅限设备,仅限发布

c# - 如何告诉调试器不要停止一些关键线程?

swift - 协议(protocol)不符合自身?

c - OpenMP 通用 qsort 加速效果不佳

c# - .NET 中的 SetForegroundWindow 问题

c# - MVC5 中无法访问自定义 IPrincipal

c# - 显示 ConnectionString 对话框

.net - 为什么在 vb.net 中如果我为单个变量分配一个数字它不等于相同的值

c# - 在 C# 程序中,程序什么时候结束执行?

java - 列表<列表<? super String> 没有按预期工作