是否有可能解构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;发布于 2017-11-10 06:58:56
您可以使用解构,但应该为此目的使用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类:(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;
}https://stackoverflow.com/questions/47217213
复制相似问题