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.
这篇关于可以从一个元组初始化多个变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:可以从一个元组初始化多个变量吗?


- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01