Jef*_*tin 20
重载是单个方法或运算符的多个可能"签名"的定义.每个签名都采用不同的参数,并且本质上是一个独特的函数,与多个函数具有不同的名称没有区别.这通常是用来组概念类似的操作,如超载+
一起工作BigInteger
,并与String
:两个操作似乎合理使用+
的(除非你认为+的所有重载应该定义Abel群 -对String
超载没有).
覆盖是相同方法签名的多个可能实现的定义,这样实现由第0个参数的运行时类型确定(通常由this
C#中的名称标识).
隐藏是派生类型中方法的定义,其签名与其基本类型中的签名相同,但不覆盖.
覆盖和隐藏之间的实际区别如下:
this
.this
.Mar*_*ell 13
重载提供了多个具有相同名称和不同签名的方法:
void Foo() {...}
void Foo(int i) {...}
Run Code Online (Sandbox Code Playgroud)
在继承中使用覆盖来更改每个子类的实现:
class SomeBase {
public virtual void Foo() {}
}
class SomeOther : SomeBase {
public override void Foo() {
// different implementation, possibly calling base.Foo();
}
}
Run Code Online (Sandbox Code Playgroud)
有了上述,即使我这样做:
SomeBase obj = new SomeOther();
obj.Foo();
Run Code Online (Sandbox Code Playgroud)
它将调用SomeOther.Foo
实现.调用的方法取决于实例类型,而不是变量.
方法隐藏是相反的; 它取代了方法签名,但仅在从派生类型调用方法时才适用:
class SomeBase {
public void Foo() {}
}
class SomeOther : SomeBase {
public new void Foo() {
// different implementation, possibly calling base.Foo();
}
}
Run Code Online (Sandbox Code Playgroud)
现在:
SomeOther obj = new SomeOther();
SomeBase baseObj = obj;
obj.Foo(); // calls SomeOther.Foo
baseObj.Foo(); // calls SomeBase.Foo
Run Code Online (Sandbox Code Playgroud)
即方法调用取决于变量,而不是实例.
重载是指使用不同参数创建多个方法时.例如:
public class Car { public Car() { // Do stuff } public Car(int numberOfCylinders) { // Do stuff } }
您可以看到构造函数具有相同的名称,但参数不同.您将在Intellisense中的Visual Studio中看到重载的方法和构造函数,上面和下方都有小箭头,因此您可以浏览签名.
覆盖是指从基类向方法提供新实现时.例:
public class Square { public double x; // Constructor: public Square(double x) { this.x = x; } public virtual double Area() { return x*x; } } class Cube: Square { // Constructor: public Cube(double x): base(x) { } // Calling the Area base method: public override double Area() { return (6*(base.Area())); } }
请注意,在C#中,您无法覆盖非虚拟或静态方法.