Possible to initialize multiple variables from a tuple?(可以从一个元组初始化多个变量吗?)
问题描述
在某些语言(例如 PHP、Haskell 或 Scala)中,您可以通过类似于以下伪代码的方式从元组中分配多个变量:
In some languages (such as PHP, Haskell, or Scala), you can assign multiple variables from tuples in a way that resembles the following pseudocode:
list(string value1, string value2) = tupleWithTwoValues;
我找不到在 C# 中执行此操作的方法,但是,如果不编写更长、更丑陋的代码:
I can't find a way to do this in C#, however, without writing longer, uglier code:
string firstValue = tupleWithTwoValues.Item1;
string secondValue = tupleWithTwoValues.Item2;
这种两行方案显然不是世界末日,但我一直在寻找编写更漂亮代码的方法.
This two-line solution is obviously not the end of the world, but I'm always looking for ways to write prettier code.
有人知道更好的方法吗?
Does anyone know a better way to do this?
推荐答案
现在可以在 C# 7 中使用:
This is now available in C# 7:
public (string first, string last) FullName()
{
return ("Rince", "Wind");
}
(var first, var last) = FullName();
您甚至可以使用单个 var 声明:
You can even use a single var declaration:
var (first, last) = FullName();
官方文档中有关解构元组的更多信息.
More on destructuring tuples in the official documentation.
这篇关于可以从一个元组初始化多个变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:可以从一个元组初始化多个变量吗?


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