2012-10-02 33 views
2

可能重複:
What are Virtual Methods?爲什麼虛方法

在C#中,即使你不申報的基類方法,如虛擬化,編譯器總是調用最新的派生類的方法時,方法簽名匹配。 如果沒有virtual關鍵字,我們只會得到警告消息,說明派生方法將被調用(現在可以通過使用new關鍵字來刪除)。

當沒有這個關鍵字時,聲明該方法爲virtual的用法也是當簽名匹配時調用最後一個派生類中的方法。

我不理解這裏的東西。代碼可讀性的目的是「虛擬」嗎? Smith

+1

[MSDN:虛擬](http://msdn.microsoft.com /en-us/library/9fkccyh4(v=vs.71).aspx) –

+1

你在說_shadowing_。這與重寫不同。請參見[MSDN](http://msdn.microsoft.com/zh-cn/library/ms172785.aspx)和[here](http://stackoverflow.com/questions/392721/difference-between-shadowing-and -over-in-in-c) – Oded

回答

0

虛擬方法可以重新定義。在C#語言中,virtual關鍵字指定了可以在派生類中重寫的方法。這使您可以添加新的派生類型,而無需修改程序的其餘部分。對象的運行時類型因此決定了程序的功能。

你可以看到一個細節example

public class Base 
{ 
    public int GetValue1() 
    { 
    return 1; 
    } 

    public virtual int GetValue2() 
    { 
    return 2; 
    } 
} 

public class Derived : Base 
{ 
    public int GetValue1() 
    { 
    return 11; 
    } 

    public override int GetValue2() 
    { 
    return 22; 
    } 
} 

Base a = new A(); 
Base b = new B(); 

b.GetValue1(); // prints 1 
b.GetValue2(); // prints 11 
+0

我明白「虛擬」方法的工作原理。我的觀點是沒有這個關鍵字的行爲是相同的,除了一個警告信息。換句話說,我可以在不使用關鍵字的情況下獲得「虛擬」方法實施的全部好處。使用這個關鍵字是更好的做法嗎? – user1492518

+0

不,事情工作完全不同。 「虛擬」不是句法糖。請閱讀我的回覆。 –

+0

@ user1492518看看這個例子。 –

5

它不是真的關於「最新派生的方法」。這是關於當你使用多態時會發生什麼。當您在預期父類的上下文中使用派生類的實例時,如果您不使用virtual/override,它將調用父類的方法。

實施例:

class A 
{ 
    public int GetFirstInt() { return 1; } 
    public virtual int GetSecondInt() { return 2; } 
} 

class B : A 
{ 
    public int GetFirstInt() { return 11; } 
    public override int GetSecondInt() { return 12; } 
} 

A a = new A(); 
B b = new B(); 

int x = a.GetFirstInt(); // x == 1; 
x = a.GetSecondInt(); // x == 2; 
x = b.GetFirstInt();  // x == 11; 
x = b.GetSecondInt(); // x == 12; 

但有以下兩種方法

public int GetFirstValue(A theA) 
{ 
    return theA.GetFirstInt(); 
} 

public int GetSecondValue(A theA) 
{ 
    return theA.GetSecondInt(); 
} 

發生這種情況:

x = GetFirstValue(a); // x == 1; 
x = GetSecondValue(a); // x == 2; 
x = GetFirstValue(b); // x == 1!! 
x = GetSecondValue(b); // x == 12 
+0

謝謝你這樣一個很好的例子。 – user1492518