将函数调用作为参数传递给另一个函数时如何解构函数调用

我想将一个返回两个值的函数传递给另一个需要相同的两个值作为参数的函数。在下面的示例中,我想将 GetNum 传递给 GetLine。


public class Program

{

    public static void Main()

    {

        Console.WriteLine(GetLine(GetNum()));

    }   

    public static (int,string) GetNum() => (5,"five");

    public string GetLine(int n , string s) => $"{n} {s}";

}

有任何 C# 语法可以帮助我吗?


慕森卡
浏览 93回答 4
4回答

慕妹3146593

函数仅返回一个值(即 one&nbsp;Type),在本例中GetNum返回 a&nbsp;ValueTuple<int, string>。允许该GetLine方法使用 的返回类型的一种GetNum方法是编写该方法的重载,该方法接受 a并将传递andValueTuple<int, string>的结果返回到原始方法:Item1Item2public&nbsp;string&nbsp;GetLine((int,&nbsp;string)&nbsp;t)&nbsp;=>&nbsp;GetLine(t.Item1,&nbsp;t.Item2);现在您可以使用一个方法的返回值作为第二个方法的参数:var&nbsp;result&nbsp;=&nbsp;GetLine(GetNum());

红糖糍粑

没有任何 C# 语法可以真正满足您的需求。具有两个参数的方法(例如您的GetLine()方法)需要向其传递两个参数,而 C# 不提供解构元组的方法,除非解构为特定变量。由于方法的参数只是值(按引用参数除外),因此没有变量可用于解构元组。有很多不同的方法可以做类似的事情。然而,恕我直言,最接近你想做的事情看起来像这样:static class Extensions{&nbsp; &nbsp; public static TResult CallDeconstructed<T1, T2, TResult>(this (T1, T2) tuple, Func<T1, T2, TResult> func)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return func(tuple.Item1, tuple.Item2);&nbsp; &nbsp; }}即,您可以在元组上调用扩展方法,它将元组的各个值作为单独的方法参数传递给所提供的方法。使用了这样的东西:public static void Main(){&nbsp; &nbsp; //Console.WriteLine(GetLine(GetNum()));&nbsp; &nbsp; Console.WriteLine(GetNum().CallDeconstructed(GetLine));}public static (int, string) GetNum() => (5, "five");public static string GetLine(int n, string s) => $"{n} {s}";尽管如此,我不确定任何替代方案(包括上述方案)是否真的比在调用站点编写中间代码好得多:(int n, string s) = GetNum();GetLine(n, s);

慕田峪7331174

你可以这样做:public static void Main(){&nbsp; &nbsp; Console.WriteLine(GetLine(GetNum()));}&nbsp; &nbsp;public static (int,string) GetNum() => (5,"five");public static string GetLine((int, string) a) {&nbsp; &nbsp; var (number, text) = a;&nbsp; &nbsp; return $"{number}, {text}";}为什么这有效?(int, string)函数的 in 参数实际上GetLine是一个类型,就像floator一样double。因此,实际就地解构它是没有意义的。当编写函数参数时,您不应该在那里编写任何逻辑 - 例如,您不能在那里增加一个数字。您只需列出参数类型和参数名称。

ibeautiful

有一个模板——它看起来像:&nbsp;public&nbsp;static&nbsp;string&nbsp;GetLine(Action<string,&nbsp;int>&nbsp;passedProc,&nbsp;otherParms)&nbsp;//&nbsp;etc这需要一个过程。对于一个函数,你可以这样做&nbsp;public&nbsp;static&nbsp;string&nbsp;GetLine(Function<(string,&nbsp;int)>&nbsp;passedFunc,&nbsp;otherParms)&nbsp;//&nbsp;etc然后您可以在 GetLine 过程中调用 PassedFunc 并取回元组。
打开App,查看更多内容
随时随地看视频慕课网APP