2012-07-26 80 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。这就是为什么编译器不能隐式转换它们,但作为程序员你可以明确地做到这一点。