Delegatesは、このメカニズムを提供します。あなたの例としてC#3.0でこれを行う簡単な方法はFunc<TResult>
で、TResult
はstring
と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;
}
これはコンパイルされません。 RunMethodはFuncを受け取ります Func –
@StanR:それに応じて編集されます。 –
+1はC#2.0の代替を表示します。 –