从字符串创建类的实例和调用方法 [英] Create instance of class and call method from string

查看:51
本文介绍了从字符串创建类的实例和调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我想实现:

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.

推荐答案

// 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]);

这篇关于从字符串创建类的实例和调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆