`
kxw953492793kxw
  • 浏览: 9244 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

在继承中虚类和费虚类的区别

 
阅读更多
虚方法定义:
虚方法就是可以被子类重写的方法,如果子类重写了虚方法
,那么就运行重写后的虚方法,如果没有,则就用父类的虚方法
virtual关键用于修饰方法、属性、索引或事件生命,并允许
在派生类中重写这些现象。


例如:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 虚方法
{
    class Person
    {
      
        #region  虚方法与非虚方法的不同
        //虚方法
        public virtual void Intrudction1()//重写虚方法
        {
            Console.WriteLine("这是虚方法");
            Console.WriteLine("My name is kexiwang,I am 21 years old,I am from china");
        }
       
        // 非虚方法
         public  void Intrudction2()
        {
            Console.WriteLine("这是非虚方法");
            Console.WriteLine("My name is kexiwang,I am 21 years old,I am from china");
        }
        #endregion
    }
    class Chinese : Person
    {
       
       
       
    }
    class Americal : Person
    {
       
        public override void Intrudction1()//重写虚方法
        {
            Console.WriteLine("My name is tom,I am 25 years old,I am from Amrican");
        }
        new public void Intrudction2()
        {
            Console.WriteLine("My name is tom,I am 25 years old,I am from Amrican");
        }
class Program
    {
        static void Main(string[] args)
        {           
            Chinese ch=new Chinese();
            Americal am = new Americal();
            Korean ko = new Korean();
            Person[] p = { ch, am, ko };
            for (int i = 0; i < p.Length; i++)
            {
                p[i].Intrudction1();
                p[i].Intrudction2();
            }
            Console.ReadKey();
        }
    }
    }
    class Korean : Person
    {      
        public override void Intrudction1()
        {
            Console.WriteLine("My name is putaihuan,I am 29 years old,I am from korean");
        }
        new public  void Intrudction2()
        {
            Console.WriteLine("My name is putaihuan,I am 29 years old,I am from korean");
        }
    }
}
  • 大小: 23.9 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics