2009-06-09 65 views
4

我會懷疑下面以輸出代碼:爲什麼C#從重寫屬性取代重寫屬性的值?

(我是智能表對象,並使用在智能表的方法)的.xml

代替,但是,其輸出:

(我是智能表對象並使用項的方法)的.xml

爲什麼呢?我如何強制C#從取代屬性的值?這就是爲什麼我是覆蓋的財產。

using System; 

namespace TestInhersdk234 
{ 
    public class Program 
    { 
     static void Main(string[] args) 
     { 
      SmartForm smartForm = new SmartForm(); 
      Console.ReadLine(); 
     } 
    } 

    public class SmartForm : Item 
    { 
     public SmartForm() 
     { 
      Console.WriteLine(FullXmlDataStorePathAndFileName); 
     } 

     public new string GetItemTypeIdCode 
     { 
      get 
      { 
       return String.Format("(I am a {0} object and using the method in SmartForm)", this.GetType().Name); 
      } 
     } 
    } 

    public class Item 
    { 
     public string FullXmlDataStorePathAndFileName 
     { 
      get 
      { 
       return GetItemTypeIdCode + ".xml"; 
      } 
     } 

     public string GetItemTypeIdCode 
     { 
      get 
      { 
       return String.Format("(I am a {0} object and using the method in Item)", this.GetType().Name); 
      } 
     } 
    } 
} 

回答

6

您需要的覆蓋關鍵字添加到壓倒一切的方法?

+0

謝謝,不同於PHP,:-) – 2009-06-09 13:59:10

+0

這實際上不是你的答案的100%...但它是它的一部分。 :) – 2009-06-09 14:00:08

13

你實際上不是壓倒一切的。你在隱藏。覆蓋:

class MyBase 
{ 
    public virtual void foo() {} 
} 

class MyClass : MyBase 
{ 
    public override void foo() {} 
} 
+0

如果在上面的代碼中SmartForm.GetItemTypeIdCode 隱藏屬性Item.GetItemTypeIdCode,被執行的屬性稱爲「隱藏」是很奇怪的。我會認爲這個「隱藏」屬性不會被執行。如何調和這個術語? – 2009-06-09 14:39:46

3

您希望覆蓋的項目屬性未標記爲virtual。因此,當您在SmartForm中重新定義它們時,您只是「隱藏」它們,而不是實際覆蓋它們。 (此外,您還需要SmartForm中的override關鍵字。)

檢出this guide

0

GetItemTypeIdCode不是虛擬的;你不是在壓倒它,你只是隱藏它。在這種情況下,執行哪個方法不是基於對象的動態類型,而是基於對象引用的靜態類型。在FullXmlDataStorePathAndFileName中,'this'的靜態類型是Item,而不是SmartForm,所以調用GetItemTypeIdCode的Item實現。

0

在基類的屬性應標明虛擬

也是在繼承類的屬性應標明覆蓋

也是我不知道爲什麼在你的代碼中的關鍵字新出現在屬性定義