【问题标题】:Create instance of class and call method from string创建类的实例并从字符串调用方法
【发布时间】:2015-03-13 22:02:26
【问题描述】:
String ClassName =  "MyClass"
String MethodName = "MyMethod"

我想实现:

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

我看到了一些,例如带有反射,但它们只显示,方法名称为字符串或类名称为字符串,任何帮助表示赞赏。

【问题讨论】:

  • 为什么需要这样做?我之所以问,是因为根据我的经验,大多数反思问题都是XY-Problems
  • 向我们展示您的尝试以及您遇到的问题。
  • 如果您看到一个使用反射创建类和另一个调用方法的示例,那么只需将它们组合起来,如果它不起作用,则发布代码和结果。

标签: c# reflection


【解决方案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]);

【讨论】:

    【解决方案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 });
    

    【讨论】:

      猜你喜欢
      • 2021-08-28
      • 2020-07-30
      • 1970-01-01
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多