Deconstruct a C# Tuple

泄露秘密 提交于 2020-12-08 07:07:25

问题


Is it possible to deconstruct a tuple in C#, similar to F#? For example, in F#, I can do this:

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

Is it possible to do something similar in C#? e.g.

// 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???

Or do I have to manually use Item1, Item2? e.g.

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

回答1:


You can use Deconstruction but you should use C#7 for this purpose:

Another way to consume tuples is to deconstruct them. A deconstructing declaration is a syntax for splitting a tuple (or other value) into its parts and assigning those parts individually to fresh variables

So the following is valid in 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;

The Deconstruct method can also be an extension method, which can be useful if you want to deconstruct a type that you don’t own. The old System.Tuple classes, for example, can be deconstructed using extension methods like this one: (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;
}


来源:https://stackoverflow.com/questions/47217213/deconstruct-a-c-sharp-tuple

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!