是否可以像 F# 一样在 C# 中解构元组?例如,在 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;
您可以使用解构主义 https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/但您应该使用 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
方法也可以是扩展方法,如果您想解构您不拥有的类型,这会很有用。老人System.Tuple
例如,可以使用如下扩展方法来解构类: (C# 7 中的元组解构 https://www.thomaslevesque.com/2016/08/23/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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)