2013-03-04 90 views
4

我想在委託類型中存儲函數引用以備後用。無法將方法組「'轉換爲非委託類型'System.Delegate'。你打算採用這種方法嗎?

下面是我在做什麼:

class Program 
{ 
    static void Test() 
    { 

    } 

    static void Main(string[] args) 
    { 
     Delegate t= (Delegate)Test; 
    } 
} 

在此我收到以下錯誤:

Cannot convert method group 'Test' to non-delegate type 'System.Delegate'.
Did you intend to invoke the method?

這究竟是爲什麼?

+0

代表是一個抽象類,而不是一個委託類型。你需要一個具體的委託類型,Action很好。 – 2013-03-04 15:11:03

回答

7

你真的不應該永遠使用類型Delegate儲存委託。您應該使用特定類型的委託。

在幾乎所有情況下,你可以使用ActionFunc爲您的委託類型。在這種情況下,Action是合適的:

class Program 
{ 
    static void Test() 
    { 

    } 

    static void Main(string[] args) 
    { 
     Action action = Test; 

     action(); 
    } 
} 

技術上可以通過這樣得到的Delegate一個實例:

Delegate d = (Action)Test; 

但實際上使用Delegate,而不是實際的具體類型的委託,如Action,將是困難的,因爲編譯器將不再知道方法的簽名是什麼,所以它不知道什麼參數應當傳遞給它。

5

你正在嘗試做的,是投了method groupTest的東西。根據規範,方法組唯一合法的強制轉換將其轉換爲委託類型。這可以明確地做:

var t = (Delegate)Test; 

或含蓄:

Delegate t = Test; 

然而,隨着documentation說,System.Delegate本身是......不是委託類型:

The Delegate class is the base class for delegate types. However, only the system and compilers can derive explicitly from the Delegate class or from the MulticastDelegate class. It is also not permissible to derive a new type from a delegate type. The Delegate class is not considered a delegate type; it is a class used to derive delegate types.

的編譯器檢測到這一點並抱怨。

如果要將方法組強制轉換爲委託,則必須指定帶有兼容簽名的委託類型(在本例中爲Action)。

相關問題