创建类的实例,并从字符串调用方法(Create instance of class and call

2019-10-22 06:08发布

String ClassName =  "MyClass"
String MethodName = "MyMethod"

我想实现:

var class = new MyClass; 
MyClass.MyMethod();

我看到一些例如与反思,但他们只能说明,无论是有方法的名称作为字符串或类名作为字符串,任何帮助表示赞赏。

Answer 1:

// Find a type you want to instantiate: you need to know the assembly it's in for it, we assume that all is is one assembly for simplicity
// You should be careful, because ClassName should be full name, which means it should include all the namespaces, like "ConsoleApplication.MyClass"
// Not just "MyClass"
Type type = Assembly.GetExecutingAssembly().GetType(ClassName);
// Create an instance of the type
object instance = Activator.CreateInstance(type);
// Get MethodInfo, reflection class that is responsible for storing all relevant information about one method that type defines
MethodInfo method = type.GetMethod(MethodName);
// I've assumed that method we want to call is declared like this
// public void MyMethod() { ... }
// So we pass an instance to call it on and empty parameter list
method.Invoke(instance, new object[0]);


Answer 2:

类似的东西,可能与更多的检查:

string typeName = "System.Console"; // remember the namespace
string methodName = "Clear";

Type type = Type.GetType(typeName);

if (type != null)
{
    MethodInfo method = type.GetMethod(methodName);

    if (method != null) 
    {
        method.Invoke(null, null);
    }
}

需要注意的是,如果你有参数传递,那么你就需要将改变method.Invoke

method.Invoke(null, new object[] { par1, par2 });


文章来源: Create instance of class and call method from string
标签: c# reflection