. net core dynamic calling generic method

Time:2021-5-8

In this paper, we share. Net core dynamic call generic method for your reference. The specific content is as follows


using System;
using System.Reflection;

namespace DynamicCall
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Hello World!");
      Program p = new Program();
      var ti = p.GetType().GetTypeInfo();
      var mtd = ti.GetMethod("Get");

      Console.WriteLine(mtd?.ToString() ?? "no get method.");

      var genMethod = mtd.MakeGenericMethod(typeof(int));

      var obj = genMethod.Invoke(p, new object[] { });

      Console.WriteLine(obj?.ToString() ?? "no get result.");

      Console.ReadLine();
    }

    public string Get<T>()
    {
      return typeof(T).FullName;
    }
  }
}

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.