我是一个小白,写博客只是为了自己做笔记,各位大神,如果有不对之处请提点一下,之前在我第一学期快结束时我一直想不明白为什么要使用虚方法因为如果写虚方法写的很麻烦,有的时候还不如自己写几个方法省事,所以我今天做了一个实验首先创建了一个需方法的类代码如下:
using System;
namespace 虚方法的实验
{
//创建测试类
class TEST
{
//创建动物类型字段
private string _type;
public string Type
{
get { return _type; }
set { _type = value; }
}
private string _color;
public string Color
{
get { return _color; }
set { _type = value; }
}
public TEST(string type,string color)
{
this._type = type;
this._color = color;
}
//创建基类动物“叫”的虚方法
public virtual void type()
{
Console.WriteLine("{0}的{1}在叫",_type,_color);
}
}
class dog:TEST
{
//这里使用了dog类的构造函数定义的color,并把colcr带入到了利用base调用的基类函数中
public dog(string color):base("狗",color){}
//重写动物叫方法改为dog
public override void type()
{
Console.WriteLine("{0}的{1}在汪 汪 叫",Color,Type);
}
}
class cat : TEST
{
public cat(string color) : base("猫", color){}
//重写动物叫方法改为cat
public override void type()
{
Console.WriteLine("{0}的{1}在喵喵叫",Color,Type);
}
}
}
接下来我们在看看普通类中的方法:
class 方法
{
//狗叫的方法
public void dog(string color)
{
Console.WriteLine("{0}的狗在汪汪叫",color);
}
//猫叫的方法
public void cat(string color)
{
Console.WriteLine("{0}的猫在喵喵叫",color);
}
}
详细乍看之下好像后者更加简便,而输出结果却是一样的调用如下:
static void Main(string[] args)
{
TEST dog = new dog("白se");
dog.type();
TEST cet = new cat("黄se");
cet.type();
方法 type = new 方法();
type.dog("白se");
type.cat("黄se");
Console.ReadKey();
}
结果:
但是之后我才明白虚方法是针对类的继承出现的,因为虚方法只是为了满足子类继承基类后能更好的写出子类的特性而出现的一种写法,当继承的基类的方法并不能满足子类的需求时, 这时,为了更能体现子类的特性需要用到虚方法,而在大多时候程序都趋向模块化,大多数操作是通过类的调用来完成,而继承在类中被频繁使用,那么当出现单一的基类中的方法无法详细描述子类中的特性时就必须用虚方法来进行重写,最后在声明一点虚方法从头到尾所调用的是一个方法,并非和普通方法一样是多个方法。