解构C#元组 [英] Deconstruct a C# Tuple

查看:83
本文介绍了解构C#元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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;

推荐答案

您可以使用

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

因此,以下内容在C#7中有效:

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;

Deconstruct 方法也可以是扩展方法,如果您想解构不属于您的类型,该方法将非常有用.例如,可以使用如下扩展方法对旧的 System.Tuple 类进行解构:(

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

这篇关于解构C#元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆