Tuple unrolling in C# similar to Python [duplicate]

谁说我不能喝 提交于 2019-12-10 17:37:46

问题


In Python we can unroll a tuple with similar syntax:

a, b = (1, 2)

Is there are similar structure in C#? Or accessing elements like:

Tuple<int, int> t = Tuple.Create(1, 2);
Console.Write(t.Item1);

the only possible way?


回答1:


Tuple destructuring (sometimes called "explosion"), i.e. distributing its elements over several variables, is not directly supported by the C# language.

You could write your own extension method(s):

static void ExplodeInto<TA,TB>(this Tuple<TA,TB> tuple, out TA a, out TB b)
{
    a = tuple.Item1;
    b = tuple.Item2;
}

var tuple = Tuple.Create(1, 2);
int a, b;
tuple.ExplodeInto(out a, out b);

The above example is just for pairs (i.e. tuples with two items). You would need to write one such extension method per Tuple<> size/type.

In the upcoming version of the C# language, you will likely be able to declare variables inside an expression. This might then possibly enable you to combine the last two lines of code above into tuple.ExplodeInto(out int a, out int b);.

Correction: Declaration expressions have apparently been dropped from the planned features for C# 6, or at least restricted; as a result, what I suggested above would no longer work.



来源:https://stackoverflow.com/questions/28261964/tuple-unrolling-in-c-sharp-similar-to-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!