In C #, can I find out in the base class what the children inherited from me?

I have a base class car and some classes of children, such as a car, motorcycle, etc., inherited from the car. In each class of children, there is a Go () function; Now I want to register information about each vehicle when the Go () function is triggered, and in this log I want to know what kind of car it made.

Example:

public class vehicle 
{
      public void Go()
      {
           Log("vehicle X fired");
      }
}
public class car : vehicle
{
       public void Go() : base()
       {
           // do something
       }
}

How can I find out in the Log function that the car called me during base ()? Thanks,

Omri

+5
source share
4 answers

A call GetType()from Vehicle.Go () will work, but only if Go () was actually called.

- :

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

this.GetType()

+4

:

GetType().Name
+2

Jon Skeet, , , . , - - - .

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

, . ... .NET.

, .

+2

All Articles