vendredi 22 février 2019

Call derived class function implementation from base

We have the following situation:

public interface IHandle<T> {
 void Handler(T param);
}

public abstract class AbsBase : IWasLeftOutForBrevity {
 public void SomeFunction<T>(T param) {
   // ... see question ...
 }
}

public class Derived : AbsBase, IHandle<int>, IHandle<decimal> {
 public void Handler(int param) {
   // ...
 }
 public void Handler(decimal param) {
   // ...
 }
}

In the above code, it is probably a well seen bit of code whereby a derived class implements a number of handle functions given a particular type.

We have a generic IoC container that injects instances of IWasLeftOutForBrevity and generically calls SomeFunction on the abstract base class with a given type. The SomeFunction is meant to call the associated Handler function on the Derived class as part of its operation.

Given that the base interface is IWasLeftOutForBrevity, and we use this in generic infrastructure, we don't have direct access to the Handler methods.

We would normally do something like:

GetType().InvokeMember("Handler",
 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod,
 null,
 this,
 args
);

or a similar GetType().GetMethods("Handler", ...)/GetType().GetMethod("Handler", ...) to find the method to call on the instance.

An added "complication" is that the type used in IHandle is often an implementation of a common interface.

I was wondering if there is any cleaner way of accessing the Handler methods without doing this kind of reflection (for instance trying to get away from the magic "Handler" string) that is more type safe?





Aucun commentaire:

Enregistrer un commentaire