简体   繁体   中英

Deconstruct a C# Tuple

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#? eg

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

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM