是否有C#功能可以将元组解构为另一个元组的子集字段?
public (bool, int) f1() => (true, 1);
public (double, bool, int) f2 => (1.0, f1() /*!!here!!*/);谢谢!
发布于 2020-08-27 17:19:13
目前还没有这样的C#特性,因此您必须将f2()编写为
public (double, bool, int) f2()
{
var tuple = f1();
return (1.0, tuple.Item1, tuple.Item2);
}但是,如果您真的想这样做,您可以编写一个帮助器类来组合元组:
public static class TupleCombiner
{
public static (T1, T2, T3) Combine<T1, T2, T3>(T1 item, (T2, T3) tuple)
{
return (item, tuple.Item1, tuple.Item2);
}
public static (T1, T2, T3) Combine<T1, T2, T3>((T1, T2) tuple, T3 item)
{
return (tuple.Item1, tuple.Item2, item);
}
// Etc for other combinations if needed
}如果您将using static YourNamespace.TupleCombiner;放在代码文件的顶部,您的代码将如下所示:
public static (bool, int) f1() => (true, 1);
public static (double, bool, int) f2() => Combine(1.0, f1());
public static (bool, int, double) f3() => Combine(f1(), 1.0);当然,这也适用于方法中的var声明:
public static void Main()
{
var tuple = Combine(1.0, f1());
}我不相信这样做是值得的,但这是一种选择。
还要注意的是--正如/u/Ry在评论中指出的-- Github上有a proposal for tuple "splatting",但这个提议已经有三年多的历史了(而且它看起来并不完全符合你的要求)。
https://stackoverflow.com/questions/63612208
复制相似问题