可以从元组初始化多个变量吗? [英] Possible to initialize multiple variables from a tuple?

查看:62
本文介绍了可以从元组初始化多个变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  list(字符串值1,字符串值2)= tupleWithTwoValues; 

但是,我找不到在C#中执行此操作的方法,而没有编写更长的,更丑陋的代码:

  string firstValue = tupleWithTwoValues.Item1;字符串secondValue = tupleWithTwoValues.Item2; 

这种两行解决方案显然不是世界末日,但我一直在寻找编写更漂亮代码的方法.

有人知道更好的方法吗?

解决方案

现在在C#7中可用:

  public(字符串开头,字符串结尾)FullName(){返回("Rince","Wind");}(var first,var last)= FullName(); 

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

  var(first,last)= FullName(); 

官方文档中有关解散元组的更多信息./p>

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;

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?

解决方案

This is now available in C# 7:

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

(var first, var last) = FullName();

You can even use a single var declaration:

var (first, last) = FullName();

More on destructuring tuples in the official documentation.

这篇关于可以从元组初始化多个变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆