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