Create instance of class and call method from stri

2019-08-11 00:42发布

String ClassName =  "MyClass"
String MethodName = "MyMethod"

I would like to achieve:

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

I saw some e.g. with reflection , but they only show , either having a method name as string or class name as string, any help appreciated.

标签: c# reflection
2条回答
看我几分像从前
2楼-- · 2019-08-11 01:15
// 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]);
查看更多
啃猪蹄的小仙女
3楼-- · 2019-08-11 01:26

Something similar, probably with more checks:

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);
    }
}

Note that if you have parameters to pass then you'll need to change the method.Invoke to

method.Invoke(null, new object[] { par1, par2 });
查看更多
登录 后发表回答