可以从元组初始化多个变量吗?

在某些语言(例如PHP)中,您可以以类似于以下伪代码的方式自动从元组中分配多个变量:

list(string value1, string value2) = tupleWithTwoValues; 

我在C#中找不到任何方法可以做到这一点,但是,如果不写更长,更丑陋的代码:

 string firstValue = tupleWithTwoValues.Item1; string secondValue = tupleWithTwoValues.Item2; 

这个两线解决方案显然不是世界末日,但我一直在寻找编写更漂亮代码的方法。 有没有人有更好的方法来做到这一点?

有效期至C#6:

不,这是不可能的。 C#中没有这样的语言function。

如果您认为以下代码:

 string firstValue = tupleWithTwoValues.Item1; string secondValue = tupleWithTwoValues.Item2; 

很难看,那么你应该首先重新考虑使用元组。


更新:从C#7开始,现在可以进行元组解构。 有关更多信息,请参阅文档 。

另见贾里德的答案 。

现在可以在C#7中使用它:

 public (string first, string last) FullName() { return ("Rince", "Wind"); } (var first, var last) = FullName(); 

您甚至可以使用单个var声明:

 var (first, last) = FullName(); 

尽管字符数几乎相同,但您可以使用以下语法在单个语句而不是两个语句中执行此操作。

 string firstValue = tupleWithTwoValues.Item1 , secondValue = tupleWithTwoValues.Item2; 

不是这在C#中不受支持,尽管其他人建议添加这样的function( 此处和此处 )。

它由F#支持,但是:

 let (f, b) = ("foo", "bar") 

当涉及到列表时,你可以这样做:

 var list = new List{tuple.Item1, tuple.Item2}; 

(这不是那么罗嗦)但对于多个变量,没有。 你不能这样做。

这就是我做的:

 public static TResult Select(this Tuple source, Func selector) { return selector(source.Item1, source.Item2); } // this allows us ... GetAssociationAndMember().Select((associationId,memberId) => { // do things with the aptly named variables }); 

是的,可以在C#中使用。 您需要在项目中安装Value.Tuple包。 你可以这样做

 List>() lstTuple = GetYourTupleValue(); foreach(var item in lstTuple) { (string Value1, string Value2 ) = item; } Console.WriteLine(item.Value1);