【问题标题】:Deconstruct a C# Tuple解构 C# 元组
【发布时间】:2017-11-10 06:55:05
【问题描述】:

是否可以在 C# 中解构元组,类似于 F#?例如,在 F# 中,我可以这样做:

// in F#
let tupleExample = (1234,"ASDF")
let (x,y) = tupleExample
// x has type int
// y has type string

是否可以在 C# 中做类似的事情?例如

// in C#
var tupleExample = Tuple.Create(1234,"ASDF");
var (x,y) = tupleExample;
// Compile Error. Maybe I can do this if I use an external library, e.g. LINQ???

还是我必须手动使用 Item1、Item2?例如

// in C#
var tupleExample = Tuple.Create(1234,"ASDF");
var x = tupleExample.Item1;
var y = tupleExample.Item2;

【问题讨论】:

  • 您说的是“编译错误”,请告诉我们哪个错误,以及您使用的 Visual Studio 版本和/或 C# 编译器版本。

标签: c# f# tuples


【解决方案1】:

您可以使用Deconstruction,但您应该为此使用C#7:

另一种使用元组的方法是解构它们。一个解构 声明是将元组(或其他值)拆分为的语法 它的部分并将这些部分单独分配给新变量

所以以下内容在 C#7 中有效:

var tupleExample = Tuple.Create(1234, "ASDF");
//Or even simpler in C#7 
var tupleExample = (1234, "ASDF");//Represents a value tuple 
var (x, y) = tupleExample;

Deconstruct 方法也可以是一个扩展方法,如果你想解构一个你不拥有的类型,它会很有用。例如,旧的System.Tuple 类可以使用如下扩展方法进行解构: (Tuple deconstruction in C# 7):

public static void Deconstruct<T1, T2>(this Tuple<T1, T2> tuple, out T1 item1, out T2 item2)
{
    item1 = tuple.Item1;
    item2 = tuple.Item2;
}

【讨论】:

猜你喜欢
  • 2017-10-10
  • 1970-01-01
  • 1970-01-01
  • 2011-08-16
  • 1970-01-01
  • 2019-07-24
  • 2015-10-31
  • 1970-01-01
  • 2018-03-06
相关资源
最近更新 更多