2011-07-19 74 views
0

好的,我有以下代碼:(從我的書中複製)。代表問題 - 基本

class MyDelegate 
{ 
    public delegate void Func(string s); 
    public void Show(string s) 
    { 
     Console.WriteLine("In MyD1: " + s); 
    } 
} 
class Test 
{ 
    static void Show(string s) 
    { 
     Console.WriteLine("In test: " + s); 
    } 
    static void Main(string[] args) 
    { 
     MyDelegate md = new MyDelegate(); 
     MyDelegate.Func f= new MyDelegate.Func(md.Show); 
     MyDelegate.Func f1= new MyDelegate.Func(Show); 
     f("hello"); 
     f1("Hello"); 
     f1 = f; 
     f1("world"); 
    } 
} 

輸出爲:In MyD1: hello In TestShow Hello InMyD1: world

現在,我不明白爲什麼輸出的最後一行是「InMyD1」。 ,因爲f1委託被調用而不是f。

在此先感謝。

+1

此外它通常是一個好習慣讓你的代碼和輸出同步。你說你的輸出中有'TestShow',但你的代碼中沒有。 – Snowbear

回答

3

您寫了f1 = f

因此,您致電f

0

f1正在重新分配f的功能參考。同樣,如果您剛分配了其他功能,例如:

f1 = s => Console.WriteLine("Another function: " + s); 

您會得到其他輸出。

0
f1 = f; 

這臺F1到f這就是爲什麼你的世界,而不是你好