I am playing around with reflection. Not sure if anyone's come up with this scenario before:
static void Main(string[] args)
{
MethodInfo definition = typeof(SafeClass).GetMethod("Print");
MethodInfo constructed = definition.MakeGenericMethod(typeof(int));
constructed.Invoke(null, null);
Console.ReadLine();
}
public class SafeClass
{
public void Print<T>()
{
Console.WriteLine(typeof(T));
}
}
I got the error Non-static method requires a target.
If I make the Print
method static, the call goes through. However, I am unsure how to invoke this call from inside static method.
Print<T>()
is an instance method, not a static method. It needs to be invoked on something.
For example, the code would be:
var sc = new SafeClass();
sc.Print<int>();
Just like you can't simply do this:
Print<int>();
You can't make reflection do it either. Either make print static, or change your code to this:
MethodInfo definition = typeof(SafeClass).GetMethod("Print");
MethodInfo constructed = definition.MakeGenericMethod(typeof(int));
constructed.Invoke(new SafeClass(), null);
Console.ReadLine();
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments