2010-07-10 97 views
5

这是更多的C#语法问题,而不是需要解决的实际问题。假设我有一个将委托作为参数的方法。比方说,我有以下方法确定:有什么办法直接使用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 */ } 

现在,如果我要打电话TakeSomeDelegatesFirstActionSecondFunc作为参数,至于我可以告诉大家,我需要做的是这样的:

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

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

+1

”虽然显然不编译“...应该编译:) – porges 2010-07-10 07:47:21

+0

woops,我真的不知道我以前做错了什么,但它现在似乎工作得很好。我想这是一个非常愚蠢的问题:S – guhou 2010-07-10 07:51:10

+0

对不起,浪费你的时间家伙...我也不确定什么答案标记为正确的......我应该删除这个问题吗? – guhou 2010-07-10 07:54:53

回答

4

你在找什么叫什么 'method groups'。与方法组替换后

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

:有了这些,可以更换一个线lamdas,如:

TakeSomeDelegates(firstAction, secondFunc); 
+0

感谢您的回答!我会接受这个,因为这个链接解释了为什么这个工作:) – guhou 2010-07-10 07:56:50

1

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

+0

请记住,它只能找出'in'参数,即它不能解决方法返回的类型:http://stackoverflow.com/questions/3203643/generic-methods-in-net-cannot-有他们的返回类型推断为什么 – 2010-07-10 07:56:19

+0

由于您不能基于返回类型重载方法组,这不是问题。 (您可以在返回类型上重载'operator implicit'和'operator explicit',但这些不能被命名为方法组)。 – 2010-07-10 09:14:56

2

只需跳过函数名称的父元素。

 TakeSomeDelegates(FirstAction, SecondFunc); 

编辑:

FYI因为括号是在VB可选的,他们有写这个...

TakeSomeDelegates(AddressOf FirstAction, AddressOf SecondFunc) 
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); 

这样你可以使用方法组。 “