有没有办法直接使用C#方法作为代理?

时间:2010-07-10 07:41:12

标签: c# syntax delegates lambda

这更像是一个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 */ }

现在,如果我想以TakeSomeDelegatesFirstAction作为参数调用SecondFunc,据我所知,我需要做类似的事情:

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

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

4 个答案:

答案 0 :(得分:4)

您正在寻找的是“method groups”。有了这些,您可以替换一行lamdas,例如:

是:

TakeSomeDelegates(x => firstAction(x), (x, y, z) => secondFunc(x, y, z));
用方法组替换后

TakeSomeDelegates(firstAction, secondFunc);

答案 1 :(得分:2)

只需跳过功能名称上的parens。

        TakeSomeDelegates(FirstAction, SecondFunc);

编辑:

仅供参考由于parens在VB中是可选的,他们必须写这个......

 TakeSomeDelegates(AddressOf FirstAction, AddressOf SecondFunc)

答案 2 :(得分:1)

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

答案 3 :(得分:0)

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

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);

通过这种方式,您可以使用方法组。

相关问题