dimanche 18 août 2019

Calling a generic method using reflection and casting correctly

I am trying to call a generic method using reflection; however I would like to know the actual type of the generic parameter within the method.

Here's the generic function I am calling

public object Get<T>() 
    {
      string typeName = typeof(T).Name;
      if (instanceManager.ContainsKey(typeName))
      {
        return instanceManager[typeName];
      }
      else
      {
        T Tinstance = (T)Activator.CreateInstance(typeof(T));
        instanceManager.Add(typeName, Tinstance);
        return Tinstance;
      }
    }

Where instanceManager is just a dictionary

Dictionary<string, object> instanceManager;

When I call this method via reflection using the code below

public static object InvokeGenericMethod(Type sourceType, string methodName, Type parameterType, object[] inputParams, object invokeOn = null)
    {
      MethodInfo methodInfo = sourceType.GetMethods().Where(item => item.IsGenericMethod).First();
      MethodInfo genericMethod = methodInfo.MakeGenericMethod(parameterType);
      object obj = genericMethod.Invoke(invokeOn, inputParams);
      return obj;
    }

The method gets called as expected, however the typeof(T) is just System.RuntimeType rather than the actual type of the generic parameter. Is there a way to retrieve the actual type name of T within the method Get() ?





Aucun commentaire:

Enregistrer un commentaire