本文介绍了在C#中,我可以知道什么样的孩子从我继承了基类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类的车辆和一些儿童类,如汽车,摩托车等。从车辆的继承。在每一个儿童类有一个函数围棋();现在我想登录的每一个车辆信息时,函数围棋()触发,并在登录我想知道哪种车辆做到了。

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

例如:

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()?Thanks,

欧米 -

推荐答案

调用 的GetType() 从Vehicle.Go()会的工作 - 但前提是围棋()实际上是一个名为

Calling GetType() from Vehicle.Go() would work - but only if Go() was actually called.

执行的一种方法是使用模板方法模式

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

这篇关于在C#中,我可以知道什么样的孩子从我继承了基类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 18:31