先写一个例子
class father
{
public void print()
{
}
}
class son:father
{
public void print(string message)
{
Console.WrileLine(message);
}
}
son myson=new son();{
public void print()
{
}
}
class son:father
{
public void print(string message)
{
Console.WrileLine(message);
}
}
son.print();//调用的是father的print方法
son.print("myson is a good boy");//调用的是son的print方法
由此可以理解虽然是方法名词相同,只要是参数不一样,程序自己可以根据语法判断使用的到底是基类的方法,还是继承后类的方法
如果参数一样呢。
2、隐藏(Hide)
当基类的方法,和继承类的方法的参数、名称一样的时候怎么办呢?
class father
{
public void print()
{
Console.WriteLine("This is father class"};
}
}
class son:father
{
public void print()
{
Console.WriteLine("This is son class");
}
}
{
public void print()
{
Console.WriteLine("This is father class"};
}
}
class son:father
{
public void print()
{
Console.WriteLine("This is son class");
}
}
如上我们的两个PRINT方法都没有参数,也符合参数一样这个条例。
那么程序编译的时候会出现C#语法方面的错误
可以使用new 关键字来实现
class son:father
{
public new void print()
{
Console.WriteLine("This is son class");
}
}
使用的时候就可以这么写
son myson=new son();
son.print()//调用的是son的print方法
base.print()//调用的是father的print方法
3、重写和虚方法
重写方法使用的是override 字段,利用virtual来定义基类的方法,然后在继承类里面使用override来重写。
class father
{
public virtual void print()
{
Console.WriteLine("this is father print()");
}
}
class son:fathre
{
public override void print()
{
Console.WriteLine("this is son print()");
}
}
{
public virtual void print()
{
Console.WriteLine("this is father print()");
}
}
class son:fathre
{
public override void print()
{
Console.WriteLine("this is son print()");
}
}
上面就是将son 里面的print()方法进行了重写;
在使用的时候
son myson=new son();
father myfather;
myfather=myson;
myson.print();//this is son print()
那么为什么要用虚方法调用机制呢?我们在面向对象编程的时候,可以在基类里面写上一个virtual方法,那么我们就可以在继承这个基类后在继承类后使用override来写我们需要他执行的事情。。