Can you name C# 7 Tuple items inline?(你能命名 C# 7 Tuple 内联项吗?)
问题描述
默认情况下,使用 C# 7 元组时,项目将命名为 Item1
、Item2
等.
By default, when using C# 7 tuples, the items will named like Item1
, Item2
, and so on.
我知道您可以命名方法返回的元组项.但是你能做同样的内联代码吗,比如下面的例子?
I know you can name tuple items being returned by a method. But can you do the same inline code, such as in the following example?
foreach (var item in list1.Zip(list2, (a, b) => (a, b)))
{
// ...
}
在 foreach
的正文中,我希望能够访问末尾的元组(包含 a
和 b
)使用比 Item1
和 Item2
更好的东西.
In the body of the foreach
, I would like to be able to access the tuple at the end (containing a
and b
) using something better than Item1
and Item2
.
推荐答案
可以,通过解构元组:
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}");
}
即使您在声明元组时命名了字段,您也需要解构语法才能将它们作为变量访问:
Even if you named the fields when declaring the tuple, you'd need the deconstruction syntax to access them as variables:
foreach (var (boo,foo) in list1.Zip(list2, (a, b) => (boo:a, foo:b)))
{
Console.WriteLine($"{boo} {foo}");
}
如果您想在不解构元组的情况下按名称访问字段,则必须在创建元组时为其命名:
If you want to access the fields by name without deconstructing the tuple, you'll have to name them when the tuple is created:
foreach (var item in list1.Zip(list2, (a, b) => (boo:a, foo:b)))
{
Console.WriteLine($"{item.boo} {item.foo}");
}
这篇关于你能命名 C# 7 Tuple 内联项吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:你能命名 C# 7 Tuple 内联项吗?


基础教程推荐
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01