随笔 - 78  文章 - 25  trackbacks - 0
<2009年10月>
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567

常用链接

留言簿

随笔分类(75)

随笔档案(78)

相册

实用Links

我的Links

搜索

  •  

积分与排名

  • 积分 - 111811
  • 排名 - 519

最新评论

阅读排行榜

评论排行榜

覆盖类成员:通过new关键字修饰虚函数表示覆盖该虚函数。
一个虚函数被覆盖后,任何父类变量都不能访问该虚函数的具体实现。
public virtual void IntroduceMyself(){...}//父类虚函数
public new void IntroduceMyself(){...}//子类覆盖父类虚函数

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MethodOverrideByNew
{
    
public enum Genders { 
        Female
=0,
        Male
=1
    }
    
public class Person {
        
protected string _name;
        
protected int _age;
        
protected Genders _gender;
        
/// <summary>
        /// 父类构造函数
        /// </summary>
        public Person() {
            
this._name = "DefaultName";
            
this._age = 23;
            
this._gender = Genders.Male;
        }
        
/// <summary>
        /// 定义虚函数IntroduceMyself()
        /// </summary>
        public virtual void IntroduceMyself() {
            System.Console.WriteLine(
"Person.IntroduceMyself()");
        }
        
/// <summary>
        /// 定义虚函数PrintName()
        /// </summary>
        public virtual void PrintName() {
            System.Console.WriteLine(
"Person.PrintName()");
        }
    }
    
public class ChinesePerson :Person{
        
/// <summary>
        /// 子类构造函数,指明从父类无参构造函数调用起
        /// </summary>
        public ChinesePerson() :base(){
            
this._name = "DefaultChineseName";
        }
        
/// <summary>
        /// 覆盖父类方法IntroduceMyself,使用new关键字修饰虚函数
        /// </summary>
        public new void IntroduceMyself() {
            System.Console.WriteLine(
"ChinesePerson.IntroduceMyself()");
        }
        
/// <summary>
        /// 重载父类方法PrintName,使用override关键字修饰虚函数
        /// </summary>
        public override void PrintName(){
            System.Console.WriteLine(
"ChinesePerson.PrintName()");            
        }
    }

    
class Program
    {
        
static void Main(string[] args)
        {
            
//定义两个对象,一个父类对象,一个子类对象
            Person aPerson = new ChinesePerson();
            ChinesePerson cnPerson 
= new ChinesePerson();
            
//调用覆盖的方法,父类对象不能调用子类覆盖过的方法,只能调用自身的虚函数方法
            aPerson.IntroduceMyself();      
            cnPerson.IntroduceMyself();
            
//调用重载方法,父类对象和子类对象都可以调用子类重载过后的方法
            aPerson.PrintName();
            cnPerson.PrintName();

            System.Console.ReadLine();
        }
    }
}

结果:
Person.IntroduceMyself()
ChinesePerson.IntroduceMyself()
ChinesePerson.PrintName()
ChinesePerson.PrintName()



posted on 2009-10-26 15:57 期待明天 阅读(719) 评论(0)  编辑  收藏 所属分类: CSharp

只有注册用户登录后才能发表评论。


网站导航: