2009-08-04 86 views
7

如何將方法作爲參數傳遞? 我一直在用JavaScript做這件事,需要使用匿名方法來傳遞參數。我如何在c#中執行此操作?將方法作爲參數

protected void MyMethod(){ 
    RunMethod(ParamMethod("World")); 
} 

protected void RunMethod(ArgMethod){ 
    MessageBox.Show(ArgMethod()); 
} 

protected String ParamMethod(String sWho){ 
    return "Hello " + sWho; 
} 

回答

13

Delegates提供這種機制。以C#3.0爲例,快速的方法是使用Func<TResult>,其中TResultstring和lambda。然後

您的代碼將變爲:

protected void MyMethod(){ 
    RunMethod(() => ParamMethod("World")); 
} 

protected void RunMethod(Func<string> method){ 
    MessageBox.Show(method()); 
} 

protected String ParamMethod(String sWho){ 
    return "Hello " + sWho; 
} 

不過,如果你使用的是C#2.0中,你可以使用匿名委託來代替:

// Declare a delegate for the method we're passing. 
delegate string MyDelegateType(); 

protected void MyMethod(){ 
    RunMethod(delegate 
    { 
     return ParamMethod("World"); 
    }); 
} 

protected void RunMethod(MyDelegateType method){ 
    MessageBox.Show(method()); 
} 

protected String ParamMethod(String sWho){ 
    return "Hello " + sWho; 
} 
+0

這不會編譯。 RunMethod需要一個Func 你傳遞給它Func 2009-08-04 17:01:36

9

你ParamMethod的類型是Func鍵<字符串,字符串>,因爲它需要一個字符串參數並返回一個字符串(請注意,角括號中的最後一項是返回類型)。

因此,在這種情況下,您的代碼會變得這樣的事情:

protected void MyMethod(){ 
    RunMethod(ParamMethod, "World"); 
} 

protected void RunMethod(Func<String,String> ArgMethod, String s){ 
    MessageBox.Show(ArgMethod(s)); 
} 

protected String ParamMethod(String sWho){ 
    return "Hello " + sWho; 
} 
+0

謝謝你的答案。我得到一個編譯錯誤'... RunMethod(Func ,String)有一些無效的參數。 – Praesagus 2009-08-04 18:00:28

+1

您使用的是哪個版本的C#? – 2009-08-04 18:32:51

4
protected String ParamMethod(String sWho) 
{ 
    return "Hello " + sWho; 
} 

protected void RunMethod(Func<string> ArgMethod) 
{ 
    MessageBox.Show(ArgMethod()); 
} 

protected void MyMethod() 
{ 
    RunMethod(() => ParamMethod("World")); 
} 

() =>是很重要的。它創建了一個來自Func<string, string>的匿名Func<string>,它是ParamMethod。

0
protected delegate String MyDelegate(String str); 

protected void MyMethod() 
{ 
    MyDelegate del1 = new MyDelegate(ParamMethod); 
    RunMethod(del1, "World"); 
} 

protected void RunMethod(MyDelegate mydelegate, String s) 
{ 
    MessageBox.Show(mydelegate(s)); 
} 

protected String ParamMethod(String sWho) 
{ 
    return "Hello " + sWho; 
} 
相關問題