使用反射从Main调用泛型方法



我在玩反射。不确定以前是否有人提出过这种情况:

    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));
    }
}

我得到了错误Non-static method requires a target.

如果我将Print方法设置为静态,则调用将通过。但是,我不确定如何从静态方法内部调用此调用。

基本上相当于下面的操作,由于显而易见的原因,这是行不通的。

null.Print<int>();

或者您打算使SafeClass.Print<T>()静态,或者您需要SafeClass的实例来调用以下方法:

var mySafeClass = new SafeClass();
constructed.Invoke(mySafeClass, null);

Print<T>()是一个实例方法,而不是静态方法。它需要在某些东西上被调用。

例如,代码为:

var sc = new SafeClass();
sc.Print<int>();

就像你不能简单地这样做:

Print<int>();

你也不能让反射做到这一点。要么将打印设置为静态,要么将代码更改为:

MethodInfo definition = typeof(SafeClass).GetMethod("Print");
MethodInfo constructed = definition.MakeGenericMethod(typeof(int));
constructed.Invoke(new SafeClass(), null);
Console.ReadLine();

它说需要一些实例来完成对这个方法的调用。我也动态地创建了对象。所以你可以运行任何包含该方法的对象。

static void Main(string[] args)
    {
        object test=  Activator.CreateInstance(typeof(SafeClass));     
        MethodInfo definition = typeof(SafeClass).GetMethod("Print");
        MethodInfo constructed = definition.MakeGenericMethod(typeof(int));
        constructed.Invoke(test, null);
        Console.ReadLine();
    }

如果该方法是实例方法或构造函数,则该方法的第一个参数应该是它自己的实例。

这是因为当调用实例方法或构造函数时,clr将隐式地将实例作为第一个参数传递给函数,以便您可以在方法中使用this

在python等其他语言中,该参数由程序员显式传递

最新更新