概述
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InheritanceApp
{
class Employee
{
public string name;
public Employee(string name)
{
this.name = name;
}
public virtual void CalculatePay()
{
Console.WriteLine("Employee.CalculatePay called for {0}",name);
}
}
class SalariedEmployee : Employee
{
public SalariedEmployee(string name)
: base(name)
{ }
//public override void CalculatePay()
//{
// Console.WriteLine("SalariedEmployee.CalculatePay called for {0} ",name);
//}
//这里将override改为new virtrual<===>virtual(new 是默认的)
public new virtual void CalculatePay()
{
Console.WriteLine("SalariedEmployee.CalculatePay called for {0} ", name);
}
}
//ContractEmployee 继承自 SalariedEmployee
class ContractEmployee : SalariedEmployee
{
public ContractEmployee(string name)
: base(name)
{ }
public override void CalculatePay()
{
Console.WriteLine("ContractEmployee.CalculatePay called for {0}", name);
}
}
class Program
{
protected Employee[] employees;
public void LoadEmployees()
{
employees = new Employee[2];
employees[0] = new ContractEmployee("Adam Barr");
employees[1] = new SalariedEmployee("Max Benson");
}
public void DoPayroll()
{
for (int i = 0; i < employees.GetLength(0); i++)
{
employees[i].CalculatePay();
}
}
public void ProcessSalariedEmployees()
{
SalariedEmployee[] se = new SalariedEmployee[2];
se[0] = new ContractEmployee("Adam Barr");
se[1] = new SalariedEmployee("Max Benson");
foreach(SalariedEmployee s in se )
{
s.CalculatePay();
}
}
static void Main(string[] args)
{
Program p = new Program();
//Employee的调用:会出现那样的结果分析:
//1.SalariedEmployee.CalculatePay的声明中添加new关键字以为着,在DoPayroll方法中遍历Employee对象引用时就不在考虑这个方法
//2.因为他是虚拟的,所以下一级别的派生类ContractEmployee中的重定义方法现在是对SalariedEmployee中的虚拟方法进行重新定义,而不是对Employee中的虚拟方法进行重新定义。
//因此ContractEmployee.CalculatePay方法也不被考虑
p.LoadEmployees();
p.DoPayroll();
//new virtual的意义:假设我们希望在一个含有所有SalariedEmployee的子集上对雇员进行分类
p.ProcessSalariedEmployees();
Console.ReadKey();
}
}
}
最后
以上就是顺利烤鸡为你收集整理的继承(六):new virtual的作用的全部内容,希望文章能够帮你解决继承(六):new virtual的作用所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复