是否有'基地'和'这个'指的是父对象字段时,,属性或方法有什么区别? [英] Is there any difference between 'base' and 'this' when referring to the parent object field, property or method?

查看:130
本文介绍了是否有'基地'和'这个'指的是父对象字段时,,属性或方法有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的代码:

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.
    }
}



之间的差异this.StartEngine(); base.StartEngine(); ,但在第二种情况下, StartEngine 方法不能移动或在城巴类中重写?是否有一个性能的影响?

Is there any difference between this.StartEngine(); and base.StartEngine();, except that in the second case, StartEngine method cannot be moved to or overridden in CityBus class? Is there a performance impact?

推荐答案

唯一的区别是显式调用看看你的父类与一个隐含的一个目的起来,通过简单的继承了同一个地方。性能差异可以忽略不计。像汉斯帕桑特说,要base.StartEngine()的调用会导致怪异的行为,如果你让虚拟StartEngine在一些点。

The only difference is an explicit call to look at your parent class versus an implicit one that ends up in the same place through simple inheritance. Performance difference is negligible. like Hans Passant said, a call to base.StartEngine() will cause weird behavior if you make StartEngine virtual at some point.

您应该不需要任何预选赛获得在正确的地方。 this.StartEngine()几乎总是多余的显式编码的时候。你可能有代码,间接地把一个这个中的对象列表的参考,但随后它被称为在列表中引用:

You shouldn't need either qualifier to get the the right place. this.StartEngine() is almost always redundant when explicitly coded. You may have code that indirectly puts a this reference in a list of objects, but then it's the reference in the list being called:

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();
    }
}

这篇关于是否有'基地'和'这个'指的是父对象字段时,,属性或方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆