我是全新的反射,我試圖從一個數據庫記錄調用類名,然後加載類並運行它,但我拉我的發出我要去哪裏的錯誤,它可能是我失蹤的真正愚蠢的東西。使用「新」關鍵字創建一個對象使用反射
作爲一個例子,我有我的課在一個不同的項目和腳本文件夾,然後從數據庫記錄調用它的名稱。
className = String.Format("Utilities.Scripts.{0}", script.ScriptClass);
然後在我的主程序我有
// Get a type from the string
Type type = Type.GetType(className);
// Create an instance of that type
Object obj = Activator.CreateInstance(type);
// Retrieve the method you are looking for
MethodInfo methodInfo = type.GetMethod("start");
// Invoke the method on the instance we created above
methodInfo.Invoke(obj, null);
但我得到的錯誤調試時,我可以看到我的信息傳遞到的GetType(類名),但沒有通過的類型去和就像這樣進入obj那裏它是錯誤的。
你能發佈你確切的錯誤嗎? –
System.ArgumentNullException - {「值不能爲空。\ r \ n參數名稱:type」} 謝謝 – Adamsk1
使用調試程序遍歷代碼並找出使用空參數調用的方法。然後,讓它們不爲空。我的第一個猜測是將methodInfo.Invoke()的第二個參數設爲空數組而不是null。 –