How to call an explicitly implemented interface-method on the base class

后端 未结 7 1200
死守一世寂寞
死守一世寂寞 2020-12-05 09:56

I have a situation, where two classes (one deriving from the other) both implement the same interface explicitly:

interface I
{
  int M();
}

class A : I
{
          


        
7条回答
  •  情书的邮戳
    2020-12-05 10:36

    Here is my version of Roland Pihlakas's nice solution. This version supports the entire inheritance chain instead of immediate base class. The Invoke method includes additional parameters and there is a void type Invoke for non-function methods.

    public class BaseClassExplicitInterfaceInvoker
    {
        readonly Dictionary Cache = new Dictionary();
    
        MethodInfo FindMethod(string MethodName)
        {
            if (Cache.TryGetValue(MethodName, out var Result)) return Result;
    
            var BaseType = typeof(T);
            while (Result == null)
            {
                if ((BaseType = BaseType.BaseType) == typeof(object)) break;
    
                var Methods = BaseType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
                Result = Methods.FirstOrDefault(X => X.IsFinal && X.IsPrivate && (X.Name == MethodName || X.Name.EndsWith("." + MethodName)));
            }
    
            if (Result != null) Cache.Add(MethodName, Result);
    
            return Result;
        }
    
        public void Invoke(T Object, string MethodName, params object[] Parameters) => FindMethod(MethodName).Invoke(Object, Parameters);
        public ReturnType Invoke(T Object, string MethodName, params object[] Parameters) => (ReturnType)FindMethod(MethodName).Invoke(Object, Parameters);
    }
    

提交回复
热议问题