2009-04-17 55 views
2

在下面的例子中,我想定義它執行的是我在運行時定義一個特定的方法System.Action,但如何傳遞方法名稱(或方法本身),所以操作方法可以定義委託來指出特定的方法?如何傳遞一個方法名來實例化一個委託?

目前,我發現了以下錯誤:

「方法名」是一個「變量」,而是使用類似「方法」

using System; 
using System.Collections.Generic; 

namespace TestDelegate 
{ 
    class Program 
    { 
     private delegate void WriteHandler(string message); 

     static void Main(string[] args) 
     { 
      List<string> words = new List<string>() { "one", "two", "three", "four", "five" }; 
      Action<string> theFunction = WriteMessage("WriteBasic"); 

      foreach (string word in words) 
      { 
       theFunction(word); 
      } 
      Console.ReadLine(); 
     } 

     public static void WriteBasic(string message) 
     { 
      Console.WriteLine(message); 
     } 

     public static void WriteAdvanced(string message) 
     { 
      Console.WriteLine("*** {0} ***", message); 
     } 

     public static Action<string> WriteMessage(string methodName) 
     { 
      //gets error: 'methodName' is a 'variable' but is used like a 'method' 
      WriteHandler writeIt = new WriteHandler(methodName); 

      return new Action<string>(writeIt); 
     } 

    } 
} 

回答

5

你並不需要委託報關或方法的WriteMessage。請嘗試以下操作:

using System; 
using System.Collections.Generic; 

namespace TestDelegate 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      List<string> words = new List<string>() { "one", "two", "three", "four", "five" }; 
      Action<string> theFunction = WriteBasic; 

      foreach (string word in words) 
      { 
       theFunction(word); 
      } 
      Console.ReadLine(); 
     } 

     public static void WriteBasic(string message) 
     { 
      Console.WriteLine(message); 
     } 

     public static void WriteAdvanced(string message) 
     { 
      Console.WriteLine("*** {0} ***", message); 
     } 

    } 
} 

操作已經是委託,因此您不需要創建另一個委託。

1

不能傳似方法除非你使用反射。爲什麼不把WriteHandler作爲參數而不是字符串?

0

你可以把它與反思工作,但不推薦。

爲什麼不把的WriteMessage方法採取WriteHandler的說法?

然後,你可以這樣調用它(在C#2+):

WriteMessage(myMethod); 
2

它傳遞無報價 -

Action<string> theFunction = WriteMessage(WriteBasic); 

變化 「的WriteMessage」 來簽名 -

public static Action<string> WriteMessage(WriteHandler methodName) 

也改變了「私人」授人以「公」 -

public delegate void WriteHandler(string message); //Edit suggested by Mladen Mihajlovic 
0

你想Delegate.CreateDelegate。在特定情況下,你想probabaly Delegate.CreateDelegate(Type,Type,string)

 
public static Action<string> WriteMessage(string methodName) 
{ 
    return (Action<string>) Delegate.CreateDelegate (
     typeof(Action<string>), 
     typeof(Program), 
     methodName); 
} 

然而,隨着姆拉登米哈伊洛維奇問,爲什麼要創建一個基於字符串的委託?這將更容易 - 並由編譯器檢查! - 使用C#支持將方法隱式轉換爲匹配簽名的委託。

相關問題