cgr*_*eno 213
超载
重载是指同一范围内有多个方法,名称相同但签名不同.
//Overloading
public class test
{
public void getStuff(int id)
{}
public void getStuff(string name)
{}
}
Run Code Online (Sandbox Code Playgroud)
重写
覆盖是一个允许您更改子类中方法功能的原则.
//Overriding
public class test
{
public virtual void getStuff(int id)
{
//Get stuff default location
}
}
public class test2 : test
{
public override void getStuff(int id)
{
//base.getStuff(id);
//or - Get stuff new location
}
}
Run Code Online (Sandbox Code Playgroud)
Dev*_*ath 34
重载和覆盖的简单定义
重载(编译时多态性)::具有相同名称和不同参数的函数
public class A
{
public void print(int x, int y)
{
Console.WriteLine("Parent Method");
}
}
public class B : A
{
public void child()
{
Console.WriteLine("Child Method");
}
public void print(float x, float y)
{
Console.WriteLine("Overload child method");
}
}
Run Code Online (Sandbox Code Playgroud)
覆盖(Run Time Polymorphism)::扩展类中的函数,其名称和参数与基类中的名称相同,但具有不同的行为.
public class A
{
public virtual void print()
{
Console.WriteLine("Parent Method");
}
}
public class B : A
{
public void child()
{
Console.WriteLine("Child Method");
}
public override void print()
{
Console.WriteLine("Overriding child method");
}
}
Run Code Online (Sandbox Code Playgroud)
cur*_*Boy 10
我想分享一个在我学习时对我很有意义的例子:
这只是一个不包含虚方法或基类的示例.只是为了暗示主要想法.
假设有一台洗车机,它有一个叫做"Wash"的功能,并接受Car作为一种类型.
获取Car输入并清洗Car.
public void Wash(Car anyCar){
//wash the car
}
Run Code Online (Sandbox Code Playgroud)
让我们重载Wash()函数
重载:
public void Wash(Truck anyTruck){
//wash the Truck
}
Run Code Online (Sandbox Code Playgroud)
洗涤功能之前只洗过一辆车,但现在它也超载了洗车.
让我们覆盖Wash()函数
重写:
public override void Wash(Car anyCar){
//check if the car has already cleaned
if(anyCar.Clean){
//wax the car
}
else{
//wash the car
//dry the car
//wax the car
}
}
Run Code Online (Sandbox Code Playgroud)
洗涤功能现在有条件检查汽车是否已经清洁并且不需要再次清洗.
如果汽车是干净的,那么只需打蜡.
如果不干净,那么先洗车,然后擦干,再打蜡
.
因此,通过添加新功能或执行完全不同的操作来覆盖功能.
| 归档时间: |
|
| 查看次数: |
155261 次 |
| 最近记录: |