代码之家  ›  专栏  ›  技术社区  ›  Reza Aghaei

包含valuetuple的结构如何能够满足非托管约束,但valuetuple本身不能满足?

  •  9
  • Reza Aghaei  · 技术社区  · 6 年前

    考虑以下类型:

    • (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
        }
    }
    

    错误CS8377类型“(int,int)”必须是不可为空的值类型, 以及任何嵌套级别的所有字段,以便将其用作 泛型类型或方法“program.dosomething()”中的参数“t”

    示例2-指针或sizeof

    使用上面的结构,指针或 sizeof 操作员:

    unsafe 
    {
        (int, int)* p1;  // → Compile-time error, 
        MyStruct* p2;    // → Compiles
    }
    

    错误CS0208无法获取的地址、大小或声明 指向托管类型(“(int,int)”的指针

    问题

    1. 结构如何包含 ValueTuple 被认为是 unmanaged 并能满足 非受管的 价值观 是否被视为管理?

    2. 结构如何具有 ValueTupple<T1, T2> 以及包含 Nullable<T> 有不同的待遇吗?


    注1: 在我看来,这个问题不同于 Proposal: Unmanaged constructed types (大卫在评论中提到),因为 MyStult 不是一般的,另一方面, int? (int,int) 两者都有管理,但是 结构mystruct int?价值; struct MyStruct { (int, int) Value; } 评价不同。

    1 回复  |  直到 6 年前
        1
  •  5
  •   JaredPar    6 年前

    谢谢你的报告。这只是编译器中的一个错误。元组用作字段时应注册为泛型类型,因此在 unmanaged type . 它似乎是作为一个郁金香评估,而错过了这项检查。

    好消息是,在C 8.0中,这一限制将消失。类型 (int, int) 是有效的 非托管类型 .

    推荐文章