gpt4 book ai didi

c# - 解构 C# 元组

转载 作者:太空狗 更新时间:2023-10-30 00:48:21 33 4
gpt4 key购买 nike

是否可以在 C# 中解构元组,类似于 F#?例如,在 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;

最佳答案

您可以使用 Deconstruction但您应该为此目的使用 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

因此以下内容在 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 类可以使用像这样的扩展方法来解构: ( 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# - 解构 C# 元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47217213/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com