c# – 引用父对象字段,属性或方法时,’base’和’this’之间有什
发布时间:2020-12-15 04:19:27 所属栏目:百科 来源:网络整理
导读:请考虑以下代码: 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 b
请考虑以下代码:
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. } } 这个.StartEngine();和base.StartEngine();,除了在第二种情况下,StartEngine方法无法在CityBus类中移动或覆盖?是否有性能影响? 解决方法
唯一的区别是显式调用查看您的父类与通过简单继承在同一个地方结束的隐式类.性能差异可以忽略不计.就像Hans Passant所说的那样,如果你在某个时候让StartEngine成为虚拟的话,调用base.StartEngine()会引起奇怪的行为.
您不应该需要任何限定符来获得正确的位置. this.StartEngine()在显式编码时几乎总是冗余的.您可能拥有间接将此引用放在对象列表中的代码,但随后它将被调用的列表中的引用: 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(); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |