先看这两个单词的含义:
override1.覆写、重载、重新定义 2.覆盖 3.改写
overload 1.超载,过载,过负荷 2.重载
因此,C#初学者常常混淆了方法重写和方法重载这两个概念。
C#方法重载:同一个作用域内发生(比如一个类里面),定义一系列同名方法,但是方法的参数列表不同。这样才能通过传递不同的参数来决定到底调用哪一个。而返回值类型不同是不能构成重载的。在方法重载上下文中,方法签名由方法名和参数列表组成(不包含返回类型),方法重载就是定义具有不同方法签名的同名方法。方法实现可以相同(例如不同类型的两个数的求和),也可以不同。
C#方法重写:继承时发生,在子类中重新定义父类中的方法,子类中的方法与父类中的方法具有相同的方法签名(在方法重写上下文中,方法签名由方法的访问级别、返回值、名称和任何方法参数)。方法实现(方法体)不同。
例如:基类方法声明为virtual(虚方法)或abstract(抽象方法),派生类中使用override申明此方法的重写。虚方法有方法实现,抽象方法没有方法实现。
C#方法隐藏:在派生类中可以定义与父类有相同方法签名的方法,新定义的方法隐藏了父类的方法。加new修饰符是显式隐藏父类中的方法,不加new修饰符也可以,但是会报警告。
C#重载时,根据参数选择调用的方法;
关键字new和override的区别
- 两者都是修饰符关键字,new还是运算符关键字和new 约束,override只是修饰符关键字;
- 作为修饰符,两者都可修饰方法,用于在派生类中定义与基类有相同方法签名的方法,override修饰的方法必须是基类的virtual、abstract 或override 方法,new修饰符不受这样的限制;
- 是否可以这样说呢? 方法重写是在良好的面向对象设计的基础上利用继承性提高程序的可扩充性,方法隐藏是缺乏良好设计时的补救措施
例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Toverrride
{
class Program
{
public class Dimensions
{
public const double PI = Math.PI;
protected double x, y;
public Dimensions()
{
}
public Dimensions(double x, double y)
{
this.x = x;
this.y = y;
}
public virtual double Area()
{
return 100 * x * y;
}
public double length()
{
return x + y;
}
}
public class Circle : Dimensions
{
public Circle(double r)
: base(r, 0)
{
}
public override double Area()
{
return PI * x * x;
}
new public double length(int c)
{
return 2 * x * PI;
}
public void fmethod(out double a,out double l)
{
a=base.Area();
l=base.length();
}
}
class Sphere : Dimensions
{
public Sphere(double r)
: base(r, 0)
{
}
public override double Area()
{
return 4 * PI * x * x;
}
}
class Cylinder : Dimensions
{
public Cylinder(double r, double h)
: base(r, h)
{
}
public override double Area()
{
return (2 * PI * x * x + 2 * PI * x * y);
}
}
static void Main()
{
double r = 3.0, h = 5.0;
Dimensions d = new Dimensions(r, h);
Dimensions c = new Circle(r);
Circle cc = new Circle(r);
Dimensions s = new Sphere(r);
Dimensions l = new Cylinder(r, h);
double ra = 0, rl = 0;
// Display results:
Console.WriteLine("Area of Circle = {0:F2}", d.Area());
Console.WriteLine("Area of Circle C = {0:F2}", c.Area());
Console.WriteLine("Area of Circle CC = {0:F2}", cc.Area());
Console.WriteLine("length of Circle C = {0:F2}", c.length());
Console.WriteLine("length of Circle CC = {0:F2}", cc.length());
Console.WriteLine("type of C is {0}\t type of CC is {1}", c.GetType().ToString(), cc.GetType().ToString());
Console.WriteLine("Area of Sphere = {0:F2}", s.Area());
Console.WriteLine("Area of Cylinder = {0:F2}", l.Area());
cc.fmethod(out ra, out rl);
Console.WriteLine("fmethod {0}\t{1}", ra, rl);
Console.ReadKey();
}
}
}