[英]In C#, can I know in the base class what children inherited from me?
I have a base class vehicle and some children classes like car, motorbike etc.. inheriting from vehicle. 我有一个基础车和一些儿童班,如汽车,摩托车等。继承车辆。 In each children class there is a function Go();
在每个子类中都有一个函数Go(); now I want to log information on every vehicle when the function Go() fires, and on that log I want to know which kind of vehicle did it.
现在我想在Go()函数触发时记录每辆车的信息,在那个日志中我想知道哪种车辆做了。
Example: 例:
public class vehicle
{
public void Go()
{
Log("vehicle X fired");
}
}
public class car : vehicle
{
public void Go() : base()
{
// do something
}
}
How can I know in the function Log that car called me during the base()? 我如何知道在base()期间汽车给我打电话的功能? Thanks,
谢谢,
Omri 奥马里
Calling GetType()
from Vehicle.Go() would work - but only if Go() was actually called. 从Vehicle.Go()调用
GetType()
可以工作 - 但只有在实际调用Go()时才能使用。
One way of enforcing this is to use the template method pattern : 强制执行此操作的一种方法是使用模板方法模式 :
public abstract class Vehicle
{
public void Go()
{
Log("vehicle {0} fired", GetType().Name);
GoImpl();
}
protected abstract void GoImpl();
}
public class Car : Vehicle
{
protected override void GoImpl()
{
// do something
}
}
this.GetType()将为您提供当前实例的类型
这个怎么样:
GetType().Name
Jon Skeet's reply certainly gets the job done, but I for one do not really like the implementation. Jon Skeet的答复当然可以完成工作,但我真的不喜欢实施。 I prefer the following which keeps it - in my opinion - simple.
我更喜欢以下内容 - 在我看来 - 简单。
Anyway, .NET provides support for this functionality already by way of virtual methods. 无论如何,.NET已经通过虚方法提供了对此功能的支持。
public class Vehicle {
public virtual void Go() {
Log(this.GetType().Name);
}
}
public class Car : Vehicle {
public override void Go() {
base.Go();
// Do car specific stuff
}
}
public class Bus : Vehicle {
}
This will work wether you are refering to an instance by it's base class or its actual class. 这将适用于您通过它的基类或其实际类引用实例。 It does not force you to change the implementation in base clases and well... all the other object orientated niceness of .NET.
它并没有强迫你改变基础clases中的实现以及所有其他面向对象的.NET的优点。
If you have full control over the implementation of the base and derived classes, then this implementation should serve you nicely. 如果您可以完全控制基类和派生类的实现,那么这个实现应该很好地为您服务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.