问题
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