C#面向对象程序设计(6)

内容纲要

6.1 多态概述 

6.1.1 多态的概念 

多态的意思即为多种形态 

例如:人类的工作

6.1.2 多态的使用 

在 C# 中,子类使用 new 关键字来达到隐藏父类成员的目的 

示例:

class Person
{
//定义人类,包含工作方法
        public void Work()
        {
       	Console.WriteLine(" 人在工作! ");
        }
}
class Doctor : Person
{
        public new void Work()
        {
     	Console.WriteLine(" 医生的工作是看病! ");
        }
}
class Cleaner : Person
{
        public new void Work()
        {
	Console.WriteLine(" 清洁工的工作是打扫卫生! ");
        }
}
class Programmer : Person
{
        public new void Work()
       {
	Console.WriteLine(" 程序员的工作是开发软件! ");
       }
}
static void Main(string[] args)
{
        Person person = new Person();
        Doctor doctor = new Doctor();
        Cleaner cleaner = new Cleaner();
        Programmer pro = new Programmer();
        person.Work();
       doctor.Work();
       cleaner.Work();
       pro.Work();
}

6.2 多态的实现 

6.2.1 方法重写 

在面向对象思想中,多态的主要表现形式是:子类继承父类后对于同一个方法有不同的实现方式。多态的实现方式有两种:隐藏父类方法和重写父类方法

示例:

static void Main(string[] args)
{
        Person person = new Doctor();//调用 Person 类的 Work() 方法
        person.Work(); 
}

使用子类重写父类的方法

示例:

class Person
{
//父类方法定义为虚方法
        public virtual void Work()
        {
	Console.WriteLine(" 人在工作! ");
        }
}


class Doctor : Person
{
//子类重写方法
        public override void Work()
        {
	Console.WriteLine(" 医生的工作是看病! ");
        }
}
static void Main(string[] args)
{
        Person person = new Doctor();
        person.Work(); //调用 Doctor 类的 Work() 方法
}

注意!

重写方法时,子类和父类方法的返回值类型、方法名和参数必须完全相同,子类方法的可访问性不能低于父类方法 

6.2.2 多态的运用 

下面我们通过以下案例来理解多态中隐藏方法和重写方法的运行结果

示例:

class Warrior : Role
{
        public new void Attack()
        {Console.WriteLine(" 战士使用了近身物理攻击! ");}
}
class Mage: Role
{
        public override void Attack()
        {Console.WriteLine(" 法师使用了远程魔法攻击! ");}
}


class Role
{
        public virtual void Attack()
        {Console.WriteLine(" 角色使用了普通攻击! "); }
}


static void Main(string[] args)
{
        Warrior war = new Warrior();
        Mage mag = new Mage ();
        war.Attack();
        mag.Attack();
}

运营一段时间后游戏进行了升级,升级后的游戏初始不能选择职业,只能在 10 级后转职为战士或法师 

示例:

static void Main(string[] args)
{
        Role war = new Role();//10级前创建角色对象
        Role mag = new Role();
        war = new Warrior();
        mag = new Mage ();//10级后专职为战士或法师
        war.Attack();
        mag.Attack();
}

6.3密封类

6.3.1 密封类介绍 

  • 密封类使用 sealed 修饰,不能用作父类。因此,密封类主要用于防止派生子类
  • 密封类可以用来限制类的扩展性,当在程序中密封了某个类时,其他类不能从该密封类继承
  • 除非类中包含带有安全敏感信息的受保护成员,否则其他情况一般不建议使用密封类 

语法:

sealed class  类名 { } 

6.3.2 使用 sealed 修饰方法 

如果类的前面加上sealed关键字,则该类不允许被继承,如果另一个类继承该类,则继承的类会报错

使用 sealed 修饰的方法称为密封方法。密封方法是指不允许子类再次重写的方法 

总结:

  1. 在面向对象思想中,多态的主要表现形式是:子类继承父类后对于同一个方法有不同的实现方式
  2. 多态的实现方式有两种:隐藏父类方法和重写父类方法
  3. 密封类使用 sealed 修饰,不能用作父类。因此,密封类主要用于防止派生子类。密封类可以用来限制类的扩展性

给TA打赏
共{{data.count}}人
人已打赏
C#

C#面向对象程序设计(5)

2022-8-15 16:02:07

C#

C#面向对象程序设计(7)

2022-8-16 16:40:51

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
今日签到
有新私信 私信列表
搜索