mardi 27 mars 2018

Get reference to class that called virtual method in C#

Is it possible to get a reference to the class that called a virtual method, from within the method defined in the abstract class?

Basically, I have an abstract class, let's say BaseAction, and this contains a virtual method, called RetrieveData:

public abstract class BaseAction
{
    protected virtual void RetrieveData()
    {

    }
}

in the implementation, I pass this virtual method into a method as an Action, something to this effect:

public class Action: BaseAction
{
    public Action()
    {
        ActionStatement(RetrieveData);
    }
}

Is is possible to get a reference to Action class, in the RetrieveData method without having to override it in the Action class, something to this effect:

public abstract class BaseAction
{
    protected virtual void RetrieveData()
    {
        // using reflection to get a handle on instance of Action?
    }
}

The reason for this is, that I want to use this virtual method in various different type of classes, each one having an ID field which needs to be modified, but I don't want to override this virtual method in each of the 20+ action classes, just to change the ID field.

I'd like this to happen in the base class, to limit the amount of code duplication.





Aucun commentaire:

Enregistrer un commentaire