方法重載,在C#中通過虛函數(shù)來實現(xiàn),具體做法:現(xiàn)在父類中用virtual將其聲明為虛函數(shù),然后在子類中用override關(guān)鍵字來指定該函數(shù)為重載函數(shù)。重載函數(shù)必須具有父類函數(shù)中的參數(shù)個數(shù),參數(shù)類型和返回類型。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MethodOverride
{
public enum Genders {
Female=0,
Male=1
}
public class Person {
protected string _name;
protected int _age;
protected Genders _gender;
public Person() {
this._name = "default name";
this._age = 20;
this._gender = Genders.Male;
}
public virtual void IntroduceMyself() {
System.Console.WriteLine("introduce myself");
}
}
public class ChinesePerson : Person {
public ChinesePerson() : base() {
this._name = "default Chinese Name";
}
public override void IntroduceMyself()
{
System.Console.WriteLine("我叫{0},年齡{1},性別{2}",this._name,this._age,this._gender);
}
}
public class EnglishPerson : Person
{
public EnglishPerson(): base()
{
this._name = "default English Name";
}
public override void IntroduceMyself()
{
System.Console.WriteLine("My Name is{0},my age is {1},my gender is {2}", this._name, this._age, this._gender);
}
}
class Program
{
static void Main(string[] args)
{
Person aPerson = new Person();
aPerson.IntroduceMyself();
aPerson = new ChinesePerson();
aPerson.IntroduceMyself();
aPerson = new EnglishPerson();
aPerson.IntroduceMyself();
System.Console.ReadLine();
}
}
}
結(jié)果如下:
introduce myself
我叫default Chinese Name,年齡20,性別Male
My Name isdefault English Name,my age is 20,my gender is Male
posted on 2009-10-26 14:07
期待明天 閱讀(987)
評論(0) 編輯 收藏 所屬分類:
CSharp