Assume I have a static generic class. Its generic type parameters are not available until runtime. How to invoke its members?
Please see the following code snippet:
static class Utility<T>
{
public static void DoSomething() { }
}
class Tester
{
static Type GetTypeAtRuntime()
{
// return an object of type Type at runtime.
}
static void Main(string[] args)
{
Type t = GetTypeAtRuntime();
// I want to invoke Utility<>.DoSomething() here. How to do this?
}
}
Edit:
OK, this is the solution based on the responses given by two guys below. Thanks for both of you!
static class Utility<T>
{
//Trivial method
public static void DoSomething(T t) { Console.WriteLine(t.GetType()); }
}
// assume Foo is unknown at compile time.
class Foo { }
class Tester
{
static void Main(string[] args)
{
Type t = typeof(Foo);// assume Foo is unknown at compile time.
Type genType = typeof(Utility<>);
Type con = genType.MakeGenericType(new Type[] { t });
MethodInfo mi = con.GetMethod("DoSomething", BindingFlags.Static | BindingFlags.Public);
mi.Invoke(null, new object[] { Activator.CreateInstance(t) });
}
}