隐藏和密封

一、继承的类型

①、实现继承:一个类型派生于一个基类型,它拥有该基类的所有非私有字段、属性和方法。注意C#不支持多重继承,即一个类不能派生自多个基类。

②、接口继承:一个类型只继承了函数,而没有继承任何实现的代码。注意结构同样可以派生自多个接口。

二、隐藏方法

所谓隐藏方法是指子类里面有和基类一样的方法,就说子类隐藏了基类的该方法。在C#中用new关键字隐藏基类的方法,当然也可以不使用new关键,编译器会给出如下警告,以提醒代码编写者是否是有意为之,但不影响程序的运行。

Warning    1    'ConsoleTest.Boy.GetName()' hides inherited member 'ConsoleTest.People.GetName()'. Use the new keyword if hiding was intended.

在希望重写基类里面的某个方法,而基类的方法又不是虚方法(virtual)并且基类代码又不能修改可以使用此办法。隐藏对于属性同样适用。

看一个简单的例子,People类和Boy类,People类中有Name和Sex属性,而Boy类中隐藏的基类的Sex属性,始终返回Male,并隐藏了基类的WriteNameAndSex方法。

public class People
    {
        public People()
        {
            Name = "";
        }

        public People(string name, string sex)
        {
            Name = name;
            Sex = sex;
        }

        public string Name { get; set; }

        public string Sex { get; set; }

        public void WriteNameAndSex()
        {
            Console.WriteLine("People Name:{0} Sex:{1}", Name, Sex);
        }
    }

    public class Boy : People
    {
        public Boy(string name, string sex)
            :base(name, sex)
        {
        }

        public new string Sex 
        {
            get { return "Male"; }
        }

        public new void WriteNameAndSex()
        {
            Console.WriteLine("Boy Name:{0} Sex:{1} ", Name, Sex);
            base.WriteNameAndSex();
        }
    }

Main方法:

static void Main(string[] args)
        {
            People p = new People("zhstar", "Female");
            p.WriteNameAndSex();

            Boy b = new Boy("细小猛", "Female");
            b.WriteNameAndSex();

            Console.ReadLine();
        }

运行后得到下面的结果:

可见我们在Boy类隐藏了基类的属性Sex和方法WriteNameAndSex,同时又可以访问基类中被隐藏的属性和方法。

三、密封类和密封方法

当我们把类、方法或者属性标记为sealed的时候,表明这些不允许被继承和重写。对于方法和属性标记为sealed的时候,必须和override同时使用。也就是这些方法和属性在基类中必须是虚方法和虚属性。这其实很好理解,方法和属性只有声明为虚(virtual)方法和属性的时候才能被重写。如果非虚,那么sealed也就失去意义。

 

 

posted on 2012-08-17 00:35  细小猛  阅读(161)  评论(0编辑  收藏  举报