[英]Deconstruct a C# Tuple
Is it possible to deconstruct a tuple in C#, similar to F#? 是否有可能在C#中解构一个元组,类似于F#? For example, in F#, I can do this:
例如,在F#中,我可以这样做:
// 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#? 是否有可能在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? 或者我是否必须手动使用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: 您可以使用解构,但您应该使用C#7来实现此目的:
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: 所以以下内容在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. Deconstruct
方法也可以是一个扩展方法,如果你想解构一个你不拥有的类型,这个方法很有用。 The old System.Tuple
classes, for example, can be deconstructed using extension methods like this one: ( Tuple deconstruction in C# 7 ): 例如,旧的
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.