How do I distinguish between two methods with the same name and number of parameters in a generic class?

后端 未结 2 1767
情歌与酒
情歌与酒 2021-01-20 14:46

Here\'s my class:

public class MyClass
{
    public void MyMethod(T a)
    {
    }

    public void MyMethod(int a)
    {
    }
}

2条回答
  •  臣服心动
    2021-01-20 15:23

    The only way I was able to do this was to use GetGenericTypeDefinition with IsGenericParameter. In the generic type definition, one method will have IsGenericParameter set to true on the parameter. However, for closed types none of the parameters will have this as true. Then, you can't use the MethodInfo from the generic type definition to invoke the method, so I stored the index and used that to lookup the corresponding MethodInfo in the closed type.

    public class Program
    {
        public static void Main(string[] args)
        {
            bool invokeGeneric = true;
            MyClass b = new MyClass();
            var type = b.GetType().GetGenericTypeDefinition();
            int index = 0;
            foreach(var mi in type.GetMethods().Where(mi => mi.Name == "MyMethod"))
            {
                if (mi.GetParameters()[0].ParameterType.IsGenericParameter == invokeGeneric)
                {
                    break;
                }
                index++;
            }
    
            var method = b.GetType().GetMethods().Where(mi => mi.Name == "MyMethod").ElementAt(index);
            method.Invoke(b, new object[] { 1 });
        }
    }
    
    public class MyClass
    {
        public void MyMethod(T a)
        {
            Console.WriteLine("In generic method");
        }
    
        public void MyMethod(int a)
        {
            Console.WriteLine("In non-generic method");
        }
    }
    

提交回复
热议问题