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