jeudi 17 octobre 2019

Get type handle for generic class parameter

I have the following class:

namespace MyClassLibrary
{
   public class CalculatorGeneric<T>  where T : IMyInterface
   {

      public int Value1 { get; set; }
      public int Value2 { get; set; }
      public CalculatorGeneric()
      {
         Value1 = 100;
         Value2 = 200;
      }

      public int Add(int val1, int val2)
      {
         Value1 = val1; Value2 = val2;
         return val1 + Value2;
      }

      public int Multiply(int val1, int val2)
      {

         Value1 = val1; Value2 = val2;

         return Value1 * Value2;
      }

   }
}

Somewhere else in my code, I prejit all methods in my solution with the following method:

  public static void PreJitAllMethods(Type type)
  {
     // get the type of all the methods within this instance
     var methods = type.GetMethods(BindingFlags.DeclaredOnly |
                                 BindingFlags.NonPublic |
                                 BindingFlags.Public |
                                 BindingFlags.Instance |
                                 BindingFlags.Static);
     if (type.IsGenericType)
     {
       // return;
     }

     // Jit all methods
     foreach (var method in methods)
     {
        // jitting of the method happends here.
        try
        {
           if (type.IsGenericType)
              RuntimeHelpers.PrepareMethod(method.MethodHandle, new[] { typeof(object).TypeHandle });
           else
              RuntimeHelpers.PrepareMethod(method.MethodHandle);
        }
        catch  (Exception ex)
        {

        }
     }
  }

Without the where T : IMyInterface I can just pass the parameter new[] { typeof(object).TypeHandle } But my problem is, I also need to call the method RuntimeHelpers.PrepareMethod for class methods where the generic parameter contains for example where T: IMyInterface. How can I do this?





Aucun commentaire:

Enregistrer un commentaire