2014-09-23 123 views
0

考慮下面我爲自己的教育寫的代碼。我有一個主要方法,一個靜態方法和兩個類 - 持有和子狀態。子部分延續。通過引用獲取子類的值

class Program 
{ 
    static void Main(string[] args) 
    { 
     hold h = new hold(); 
     h.aa = 88; 
     Console.WriteLine("In main " + h.aa); 
     thismethod(h); 
     Console.WriteLine("In main2 " + h.aa); 
     Console.WriteLine("In main3 " + h.ss); //ERROR 

     Console.ReadKey(); 
    } 

    static void thismethod (hold h) { 
     Console.WriteLine("In thismdethod " + h.aa); 

     h.aa += 1; 
     Console.WriteLine("In thismdethod1 " + h.aa); 
     h = null; 
     subhold subhold = new subhold(); 

     subhold.aa = 8888; 
     subhold.ss = 22222; 

     h = subhold; 

    } 


} 

class hold 
{ 
    public int aa { get; set; } 

} 

class subhold : hold 
{ 
    public int ss { get; set; } 
} 

我正在試圖訪問h.ss.現在我無法訪問它。我如何從主要方法訪問h.ss

+3

幾件事,首先基類不能訪問子類的屬性/成員。第二次閱讀[Jon Skeet在C#中傳遞參數](http://www.yoda.arachsys.com/csharp/parameters.html) – Habib 2014-09-23 21:05:04

+0

'h'是'hold',而不是'subhold'。它沒有'ss'屬性。 – Blorgbeard 2014-09-23 21:07:04

+0

我也嘗試過''這種方法(ref h)'用'static void thidmethod'(ref hold h)'' – Zuzlx 2014-09-23 21:07:32

回答

2

基類沒有(也更重要的是不應該)知道派生類
屬性的任何內容。不同的派生類可以有一組不同的添加屬性。 使基類意識到這將抵消對象 爲本的設計

static void Main(string[] args) 
    { 
     subhold h = new subhold(); 
     h.aa = 88; 
     Console.WriteLine("In main " + h.aa); 
     thismethod(h); 
     Console.WriteLine("In main2 " + h.aa); 
     Console.WriteLine("In main3 " + h.ss); //no ERROR 

     Console.ReadKey(); 
    } 
1

的重要原則,如果按引用傳遞h,然後thismethod將改變主要的h指向的subhold一個實例。

Main變量h仍然聲明hold,雖然。所以你需要將它投射到subhold才能訪問ss

static void Main(string[] args) 
{ 
    hold h = new hold(); 
    h.aa = 88; 
    Console.WriteLine("In main " + h.aa); 
    thismethod(ref h); 
    Console.WriteLine("In main2 " + h.aa); 
    Console.WriteLine("In main3 " + ((subhold)h).ss); // casted, no error. 

    Console.ReadKey(); 
} 

static void thismethod (ref hold h) {     // passing by reference 
    Console.WriteLine("In thismdethod " + h.aa); 

    h.aa += 1; 
    Console.WriteLine("In thismdethod1 " + h.aa); 
    h = null; 
    subhold subhold = new subhold(); 

    subhold.aa = 8888; 
    subhold.ss = 22222; 

    h = subhold; 
} 
+0

再次感謝。好東西! – Zuzlx 2014-09-25 18:41:19