none
Executing method of the Generic class using Reflection.

    Question

  • Hi.

    I have a generic class:

     abstract public class BaseTC<T>:IExecutable where T : Core, new()
      {
        private Type2 testInfo;
        private Type1 settings;
        private T core = null;
        ..
    }
    

    and I want to load such class from library the class is located in, and create an instance of it and execute methods later on.

    I know how to use non-generic classes, but no idea how to call the same with generics.

    Saturday, October 09, 2010 8:06 AM

All replies

  • > I know how to use non-generic classes, but no idea how to call the same with generics.

    The key is MakeGenericType to obtain a Type with the generic type parameters filled in.  There is also a strange typeof syntax for obtaining the unconstructed type (see Derived<> below).  Though you can obtain this Type in a more reflective way through means such as Type.GetType, which takes a string, too.

    class Program
    {
      static void Main(string[] args)
      {
        Type u = typeof(Derived<>);
        Type c = u.MakeGenericType(typeof(int));
        object inst = Activator.CreateInstance(c);
        int ret = (int)c.GetMethod("Test").Invoke(inst, new object[] { 123 });
        Console.WriteLine(ret); // Prints 123.
      }
    }
    
    abstract public class Base<T>
    {
      public T Test(T x)
      {
        return x;
      }
    }
    
    public class Derived<T> : Base<T>
    {
    }
    
    • Marked as answer by jackbond Sunday, October 10, 2010 2:53 PM
    • Unmarked as answer by jackbond Sunday, October 10, 2010 2:53 PM
    Saturday, October 09, 2010 2:17 PM
  • hmm, yeah

    but how to load that class from assembly file?

    when i listed generic classes located in library (showed in a console using reflection), it had strange syntax

    Sunday, October 10, 2010 2:54 PM
  • bump it up, more curious
    Monday, October 11, 2010 5:16 PM