标题:求救,new关键字隐藏父类的问题?
取消只看楼主
拥抱GIS
Rank: 1
等 级:新手上路
帖 子:11
专家分:0
注 册:2008-6-5
 问题点数:0 回复次数:0 
求救,new关键字隐藏父类的问题?
class Shape
{
    public virtual void Draw()
    {
        Console.WriteLine("Shape.Draw")    ;
    }
}

class Rectangle : Shape
{
    public new void Draw()
    {
        Console.WriteLine("Rectangle.Draw");
    }            
}
class Square : Rectangle
{
    //这里不用 override
    public new void Draw()
    {
        Console.WriteLine("Square.Draw");
    }
}
class MainClass
{
    static void Main(string[] args)
    {
        Console.WriteLine("Using Polymorphism:");
        Shape[] shp = new Shape[3];
        Rectangle rect = new Rectangle();
            
        shp[0] = new Shape();
        shp[1] = rect;
        shp[2] = new Square();
                        
        shp[0].Draw();
        shp[1].Draw();
        shp[2].Draw();
            
        Console.WriteLine("Using without Polymorphism:");
        rect.Draw();            
        Square sqr = new Square();
        sqr.Draw();
    }
}   
   
Output:
Using Polymorphism
Shape.Draw
Shape.Draw
Shape.Draw
Using without Polymorphism:
Rectangle.Draw
Square.Draw


上面的代码中我有一个问题不太明白:
        shp[0] = new Shape();
        shp[1] = rect;
        shp[2] = new Square();
        shp[0].Draw();
        shp[1].Draw();
        shp[2].Draw();

        rect.Draw();            
        Square sqr = new Square();
        sqr.Draw();
都是先通过实例化对象后调用,这两个有什么区别?不是说隐藏后的基类方法只能通过基类访问调用吗?
小弟初学,还望各位大侠帮忙帮我解释解释!在此先谢过!
搜索更多相关主题的帖子: Draw new 父类 Rectangle void 
2008-06-06 11:33



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-217922-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.279507 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved