Memberinfo call generic method System.InvalidOperationException: 'Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.'

static void Main(string[] args)
{
    GenericMethod();
    LogInfo();
}

static void GenericMethod()
{
    MethodInfo mi = typeof(Program).GetMethod("Echo"); 
    Console.WriteLine(mi.IsGenericMethodDefinition); 
    Console.WriteLine(mi.Invoke(null, new object[] { 123 }));
}

public static T Echo<T>(T x)
{
    return x;
}

 

 

To remidy this issue,we must specify concrect types of generic methods.

  static void Main(string[] args)
  {
      GenericMethod();
      LogInfo();
  }

  static void GenericMethod()
  {
      MethodInfo mi = typeof(Program).GetMethod("Echo");
      MethodInfo intMi = mi.MakeGenericMethod(typeof(int));
      Console.WriteLine(intMi.IsGenericMethodDefinition); 
      Console.WriteLine(intMi.Invoke(null, new object[] { 123 }));
  }

  public static T Echo<T>(T x)
  {
      return x;
  }

 

 

The key located at specify concrete type

//MakeGenericMethod

MethodInfo intMi = mi.MakeGenericMethod(typeof(int));

  

posted @ 2024-03-09 12:33  FredGrit  阅读(72)  评论(0编辑  收藏  举报