【问题标题】:Is there any way to use C# methods directly as delegates?有没有办法直接使用 C# 方法作为委托?
【发布时间】:2010-07-10 16:59:55
【问题描述】:

这更像是一个 C# 语法问题,而不是一个需要解决的实际问题。假设我有一个将委托作为参数的方法。假设我定义了以下方法:

void TakeSomeDelegates(Action<int> action, Func<float, Foo, Bar, string> func)
{
    // Do something exciting
}

void FirstAction(int arg) { /* something */ }

string SecondFunc(float one, Foo two, Bar three){ /* etc */ }

现在,如果我想用FirstActionSecondFunc 作为参数调用TakeSomeDelegates,据我所知,我需要这样做:

TakeSomeDelegates(x => FirstAction(x), (x,y,z) => SecondFunc(x,y,z));

但是有没有更方便的方法来使用适合所需委托签名的方法而无需编写 lambda?理想情况下类似于TakeSomeDelegates(FirstAction, SecondFunc),尽管显然这不会编译。

【问题讨论】:

  • "虽然显然不能编译" ...应该编译:)
  • 哎呀,我真的不知道我以前做错了什么,但现在它似乎工作得很好。我想这是一个非常愚蠢的问题:S
  • 抱歉,你们浪费了你们的时间……我也不确定要标记为正确的答案是什么……我应该删除这个问题吗?

标签: c# syntax delegates lambda


【解决方案1】:

您要查找的是名为“method groups”的内容。有了这些,就可以替换一行lamdas,如:

曾经:

TakeSomeDelegates(x => firstAction(x), (x, y, z) => secondFunc(x, y, z));

用方法组替换后:

TakeSomeDelegates(firstAction, secondFunc);

【讨论】:

  • 感谢您的回答!我将接受这一点,因为链接解释了为什么这样做:)
【解决方案2】:

只需跳过函数名称上的括号。

        TakeSomeDelegates(FirstAction, SecondFunc);

编辑:

仅供参考,因为括号在 VB 中是可选的,所以他们必须这样写...

 TakeSomeDelegates(AddressOf FirstAction, AddressOf SecondFunc)

【讨论】:

    【解决方案3】:

    编译器将接受需要委托的方法组的名称,只要它能够确定选择哪个重载,您就不需要构建 lambda。您看到的确切编译器错误消息是什么?

    【讨论】:

    • 请记住,它只能找出“in”参数,即它无法解析方法返回的类型:stackoverflow.com/questions/3203643/…
    • 由于您不能根据返回类型重载方法组,这不是问题。 (您可以在返回类型上重载 operator implicitoperator explicit,但不能将它们命名为方法组)。
    【解决方案4】:

    是的,它被称为方法组,更准确的例子是......

    static void FirstAction(int arg) { /* something */ }
    
    static string SecondFunc(float one, Foo two, Bar three) { return ""; }
    
    
    Action<int> act1 = FirstAction;
    Func<float, Foo, Bar, string> act2 = SecondFunc;
    
    
    TakeSomeDelegates(firstAction, secondFunc);
    

    这样你就可以使用方法组了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多