创建 class 的实例并从字符串调用方法
Create instance of class and call method from string
String ClassName = "MyClass"
String MethodName = "MyMethod"
我想达到:
var class = new MyClass;
MyClass.MyMethod();
我看到了一些,例如有反射,但它们只显示,方法名称为字符串或 class 名称为字符串,任何帮助表示赞赏。
// 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]);
类似的东西,可能需要更多检查:
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 });
String ClassName = "MyClass"
String MethodName = "MyMethod"
我想达到:
var class = new MyClass;
MyClass.MyMethod();
我看到了一些,例如有反射,但它们只显示,方法名称为字符串或 class 名称为字符串,任何帮助表示赞赏。
// 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]);
类似的东西,可能需要更多检查:
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 });