C# 函数重载

C# 函数重载
方法重载,在C#中通过虚函数来实现,具体做法:现在父类中用virtual将其声明为虚函数,然后在子类中用override关键字来指定该函数为重载函数。重载函数必须具有父类函数中的参数个数,参数类型和返回类型。

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();
        }
    }
}

结果如下:
introduce myself
我叫default Chinese Name,年龄20,性别Male
My Name isdefault English Name,my age is 20,my gender is Male



你可能感兴趣的:(C# 函数重载)