2010-03-16 36 views
7

的覆蓋getter我有一個基類「父」是這樣的:呼叫「基地拼命三郎」物業

using System; 
using System.Collections.Generic; 
using System.Text; 

namespace ConsoleApplication1 
{ 
    class Parent 
    { 
     private int parentVirtualInt = -1; 
     public virtual int VirtualProperty 
     { 
      get 
      { 
       return parentVirtualInt; 
      } 
      set 
      { 
       if(parentVirtualInt != value) 
       { 
        parentVirtualInt = value; 
       } 
      } 
     } 
    } 
} 

和子類是這樣的:

using System; 
using System.Collections.Generic; 
using System.Text; 

namespace ConsoleApplication1 
{ 
    class Child : Parent 
    { 
     public override int VirtualProperty 
     { 
      get 
      { 
       if(base.VirtualProperty > 0) 
       { 
        throw new ApplicationException("Dummy Ex"); 
       } 
       return base.VirtualProperty; 
      } 
      set 
      { 
       if(base.VirtualProperty != value) 
       { 
        base.VirtualProperty = value; 
       } 
      } 
     } 
    } 
} 

請注意getter在Child中調用Parent的getter(或者至少這是我的意圖)。

我現在使用「Child」類來實例化它,給它的VirtualProperty分配一個值(假設爲4),然後再次讀取該屬性。

Child c = new Child(); 
c.VirtualProperty = 4; 
Console.Out.WriteLine("Child.VirtualProperty: " + c.VirtualProperty); 

當我運行這個,我顯然得到一個ApplicationException說「虛擬Ex」。 ,如果我在孩子設置一個斷點上線

if(base.VirtualProperty > 0) 

,並檢查base.VirtualProperty值(通過將鼠標懸停吧)的異常可能拋出之前(我假設(d)),我已經得到例外。從這裏我傳達出在「兒童吸氣者自稱」中陳述base.VirtualProperty;有點。

我想要達到的效果與將parentVirutalInt(在父級中)的定義更改爲受保護並在子的Getter中使用base.parentVirtualInt而不是base.VirtualProperty時得到的行爲相同。我還不明白爲什麼這不起作用。任何人都可以對此有所瞭解嗎?我覺得重寫的屬性的行爲不同於重寫的方法嗎?順便說一句:我正在做一些非常類似於繼承一個我沒有任何控制權的類(這是我的「解決方法」不是一個選項)的主要原因。

親切的問候

回答

8

這是(可以說)在調試器中的錯誤。您可以將您的投票添加到此feedback article。這是不容易解決的,我敢肯定,調試器沒有對基本屬性getter方法地址的訪問,因爲屬性getter的v-table插槽已經在派生類中被替換。

一種可能的解決方法是首先將基本值存儲在局部變量中,以便您可以檢查該值。這不會讓你的getter變慢。