2012-07-26 88 views
0
class Program 
{ 
    static void Main(string[] args) 
    { 

     Father objFather = new Son(); //Ok compiles 

     Son objSon1 = new Father(); //Comile time error : Cannot implicitly convert type 

     Son objSon = (Son)new Father(); //Run time error 
     Console.ReadLine(); 
    } 
} 

class Father 
{ 
    public void Read() 
    { 

    } 

} 

class Daughter:Father 
{ 

} 

class Son:Father 
{ 

} 

任何人都可以解釋爲什麼它是什麼?內存中發生了什麼?派生類不能引用父類

+1

也許你想在提出具體問題之前閱讀關於OOP的一些基本概念,如[inheritance](http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming))。 – 2012-07-26 15:16:42

回答

1

你似乎誤解了繼承。

每個Daughter和每個SonFather。這就是爲什麼你可以安全地分配一個Father變量。一個子類不能刪除只添加它們的屬性/方法,這就是爲什麼它確定它始終在工作。

但是當你有Father一個實例,並希望將其分配給一個變量Son,你不能確保實例是Son,實際上具有所需的所有屬性。 Father實例也可能包含與Son不兼容的Daughter。這就是爲什麼編譯器不能隱式轉換它們,但作爲程序員你可以明確地做到這一點。