C# .NET Take Action 作为方法的参数,该方法提供可以从 lambda

为了简化我刚刚写的内容,基本上意味着我想要这样的东西:


var someClass = new someClass((func1, func2) =>

{

  if (cool)

  {

    func1(cool);

  }

  else

  {

    func2(cool);

  }

}

这可能吗?我尝试了一个动作,但没有用。我真的很感激一些帮助:D


慕无忌1623718
浏览 288回答 3
3回答

缥缈止盈

好的,我希望这是您正在寻找的:&nbsp; public class SomeClass{&nbsp; &nbsp; public SomeClass(Action<Action<bool>, Action<bool>> func)&nbsp; &nbsp; {&nbsp; &nbsp; func(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (i) =>{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Func1(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (j) =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Func2(j);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; &nbsp; public void Func1(bool cool)&nbsp; &nbsp; {&nbsp; &nbsp; }&nbsp; &nbsp; public void Func2(bool cool)&nbsp; &nbsp; {&nbsp; &nbsp; }&nbsp; &nbsp; public static void Main()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var someClass = new SomeClass((func1, func2) =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var cool = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (cool)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; func1(cool);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; func2(cool);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }}

ITMISS

&nbsp;var f = new Func<int>(() => { return 1; });&nbsp;var result = f.Invoke();这就是你所追求的吗?输入和输出的语法是var myfunction = new Func((x,y,z) => { return a;});var a = x.Invoke(x,y,z);来自编辑评论&nbsp;public class someclass&nbsp;{&nbsp; &nbsp; &nbsp; private Func A = ......&nbsp; &nbsp; &nbsp; private Func B = ......&nbsp; &nbsp; &nbsp; public void somemethod(type x)&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(x) this.A.Invoke();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;else this.B.Invoke();&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; }&nbsp;}

萧十郎

您可以创建一个接受 Action 参数并根据某些条件返回其中一个参数的方法,以便可以在调用站点执行返回的 Action。Action method (Action a, Action b){&nbsp; &nbsp; if (cool)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return a;&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return b;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP