If I have a MethodInfo on a closed generic Type is there an easy way to switch those types?

前端 未结 4 1460
醉酒成梦
醉酒成梦 2020-12-06 12:26

Let\'s say that I have the methodInfo for something like Nullable.HasValue. Is there anyway to convert it to Nullable.HasValue

4条回答
  •  抹茶落季
    2020-12-06 12:50

    Solved it. But the big question is this a safe way to do it? Is there something I could be doing wrong here?

        public static MethodInfo Convert(this MethodInfo method,params Type[] DeclaringTypeArguments)
        {
            var baseType = method.DeclaringType.GetGenericTypeDefinition().MakeGenericType(DeclaringTypeArguments);
            return MethodInfo.GetMethodFromHandle(method.MethodHandle, baseType.TypeHandle) as MethodInfo;
        }
        public static void Main(String[] args)
        {
            List list = new List(); 
            Action action  = list.Add;
            Console.WriteLine(action.Method.Convert(typeof(string)));
            Console.Read();
        }
    

提交回复
热议问题