【问题标题】:Can you name C# 7 Tuple items inline?你能命名 C# 7 Tuple 内联项吗?
【发布时间】:2017-09-24 23:40:06
【问题描述】:

默认情况下,使用 C# 7 元组时,项目将命名为 Item1Item2 等。

我知道你可以name tuple items being returned by a method。但是你能做同样的内联代码吗,比如下面的例子?

foreach (var item in list1.Zip(list2, (a, b) => (a, b)))
{
    // ...
}

foreach 的正文中,我希望能够使用比Item1Item2 更好的方式访问末尾的元组(包含ab)。

【问题讨论】:

    标签: c# tuples c#-7.0


    【解决方案1】:

    是的,你可以通过解构元组:

    foreach (var (boo,foo) in list1.Zip(list2, (a, b) => (a, b)))
    {
        //...
        Console.WriteLine($"{boo} {foo}");
    }
    

    foreach (var item in list1.Zip(list2, (a, b) => (a, b)))
    {
        //...
        var (boo,foo)=item;
        Console.WriteLine($"{boo} {foo}");
    }
    

    即使您在声明元组时命名了字段,您也需要解构语法才能将它们作为变量访问:

    foreach (var (boo,foo) in list1.Zip(list2, (a, b) => (boo:a, foo:b)))
    {
        Console.WriteLine($"{boo} {foo}");
    }
    

    如果您想在不解构元组的情况下按名称访问字段,则必须在创建元组时为其命名:

    foreach (var item in list1.Zip(list2, (a, b) => (boo:a, foo:b)))
    {
        Console.WriteLine($"{item.boo} {item.foo}");
    }
    

    【讨论】:

    • 这太棒了,我已经阅读了有关 C# 7 元组的各种文章,但没有看到任何地方记录的冒号语法。
    • @Gigi 你可能在这些文章的“解构”部分做过。 任何 类型都可以通过这种方式解构,只要它具有Deconstruct 成员或扩展 方法。元组很适合这种情况。您可以为现在没有的类型创建扩展解构方法,例如 KeyValuePair 只是乞求void Deconstruct<TK,TV>(this KeyValuePair,out TK key, out TV value) ... 方法
    • refoutref local 的新元组语法的示例用法可以在here 找到
    【解决方案2】:

    请注意,C# 7.1 将对元组名称进行改进。不仅可以显式命名元组元素(使用名称-冒号语法),而且可以推断出它们的名称。这类似于匿名类型中成员名称的推断。

    例如,var t = (a, this.b, y.c, d: 4); // t.a, t.b, t.c and t.d exist

    更多详情请见https://github.com/dotnet/csharplang/blob/master/proposals/csharp-7.1/infer-tuple-names.md

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      • 2020-08-19
      相关资源
      最近更新 更多