2009-08-04 25 views
7

メソッドを引数として渡すにはどうすればよいですか? 私はこれをJavascriptで常に行い、匿名メソッドを使用してparamsを渡す必要があります。 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とlambdasです。

あなたのコードは、その後になる:あなたがC#2.0を使用している場合は

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

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

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

しかし、あなたの代わりに匿名デリゲートを使用することもできます。

// 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

+0

@StanR:それに応じて編集されます。 –

+0

+1はC#2.0の代替を表示します。 –

7

それは1つの文字列引数を取り、文字列を返すので、あなたのParamMethodは(タイプのFunc <文字列、文字列>であるC#デリゲート

http://msdn.microsoft.com/en-us/library/ms173171(VS.80).aspx

チュートリアルhttp://www.switchonthecode.com/tutorials/csharp-tutorial-the-built-in-generic-delegate-declarations

+0

優れたリンクは、ありがとうございます。これはそれらの1つです:http://www.mujahiddev.com/2009/01/lambda-expressions-c.html – Praesagus

9

を見てみましょう角カッコ内の最後の項目は戻り値の型です)。

だからこの場合は、あなたのコードは次のようになる:

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

+1

使用しているC#のバージョンは? –

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

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

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

() =>が重要であること。 ParamMethodであるFunc<string, string>から匿名のFunc<string>を作成します。

+0

+1これは良い例ですが、ややこしい –

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; 
} 
関連する問題