String ClassName = "MyClass"
String MethodName = "MyMethod"
我想实现:从字符串创建类和呼叫方法的实例
var class = new MyClass;
MyClass.MyMethod();
我看到一些例如用反射,但他们只显示,或者有一个方法名称作为字符串或类名字符串,任何帮助赞赏。
String ClassName = "MyClass"
String MethodName = "MyMethod"
我想实现:从字符串创建类和呼叫方法的实例
var class = new MyClass;
MyClass.MyMethod();
我看到一些例如用反射,但他们只显示,或者有一个方法名称作为字符串或类名字符串,任何帮助赞赏。
// 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]);
谢谢!工作! – 2015-03-13 14:11:15
类似的东西,可能有更多的检查:
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 });
为什么你需要要做到这一点?我在问,因为大多数反思问题都是根据我的经验[XY-Problems](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。 – 2015-03-13 13:59:21
告诉我们你已经尝试过什么,以及你在哪里受到困扰。 – adricadar 2015-03-13 14:00:01
如果您看到一个使用反射来创建类的示例,而另一个示例使用反射来调用方法,那么只需将它们组合起来,如果它不起作用,则发布代码和结果。 – juharr 2015-03-13 14:01:14