从string创建类的实例和调用方法

Zai*_*jee 1 c# reflection

String ClassName =  "MyClass"
String MethodName = "MyMethod"
Run Code Online (Sandbox Code Playgroud)

我想实现:

var class = new MyClass; 
MyClass.MyMethod();
Run Code Online (Sandbox Code Playgroud)

我看到一些例如反射,但他们只显示,或者将方法名称作为字符串或类名称作为字符串,任何帮助表示赞赏.

Ego*_*rov 7

// 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]);
Run Code Online (Sandbox Code Playgroud)


xan*_*tos 5

类似的内容,可能需要进行更多检查:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果您有要传递的参数,则需要将更method.Invoke改为

method.Invoke(null, new object[] { par1, par2 });
Run Code Online (Sandbox Code Playgroud)