String ClassName = "MyClass"
String MethodName = "MyMethod"
我想实现:
var class = new MyClass;
MyClass.MyMethod();
我看到了一些例如使用反射,但它们只显示,要么将方法名称作为字符串,要么将类名称作为字符串,以及任何帮助表示赞赏。
答案 0 :(得分:6)
// 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]);
答案 1 :(得分:4)
类似的东西,可能有更多的支票:
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 });