在引用父对象字段,属性或方法时,'base'和'this'之间有什么区别吗?

Ars*_*nko 6 c# oop syntax optimization

请考虑以下代码:

public class Vehicle
{
    public void StartEngine()
    {
        // Code here.
    }
}

public class CityBus : Vehicle
{
    public void MoveToLocation(Location location)
    {
        ////base.StartEngine();
        this.StartEngine();
        // Do other stuff to drive the bus to the new location.
    }
}
Run Code Online (Sandbox Code Playgroud)

是否有任何区别this.StartEngine();base.StartEngine();不同之处在于在第二种情况下,StartEngine方法不能被移动到或重写CityBus类?是否有性能影响?

Han*_*ant 6

没有区别,StartEngine()不是虚拟的.您不应该使用base,以防您重构它以使其成为虚拟.perf diff是不可测量的.


Kei*_*thS 3

唯一的区别是显式调用查看父类与隐式调用(通过简单继承最终到达同一位置)。性能差异可以忽略不计。就像 Hans Passant 所说,如果您在某个时刻将 StartEngine 设为虚拟,则对 base.StartEngine() 的调用将导致奇怪的行为。

您不需要任何一个预选赛即可获得正确的位置。this.StartEngine()当显式编码时几乎总是多余的。您可能有代码间接将this引用放入对象列表中,但随后调用的是列表中的引用:

public class Vehicle
{
    public void StartEngine()
    {
        // Code here.
    }

    //For demo only; a method like this should probably be static or external to the class
    public void GentlemenStartYourEngines(List<Vehicle> otherVehicles)
    {
       otherVehicles.Add(this);

       foreach(Vehicle v in Vehicles) v.StartEngine();
    }
}
Run Code Online (Sandbox Code Playgroud)