C#反射
阿新 • • 發佈:2017-05-10
reac ren odi oid rec test assembly bsp 裝載
protected void Page_Load(object sender, EventArgs e) { Invoke("Test", "1.0.0.0", "neutral", "8d7b357e8456bb71", "Test", "Class1", "GetMessage",new object[] {"1","p"}); } private string Invoke(string lpFileName, string Version, string Culture, string PublicKeyToken, stringNamespace, string ClassName, string lpProcName,object[] objArr) { string ssc = ""; try { // 載入程序集 Assembly MyAssembly = Assembly.Load(lpFileName + ", Version=" + Version + ", Culture=" + Culture + ", PublicKeyToken=" + PublicKeyToken); Type[] type= MyAssembly.GetTypes(); foreach (Type t in type) {// 查找要調用的命名空間及類 if (t.Namespace == Namespace && t.Name == ClassName) {// 查找要調用的方法並進行調用 MethodInfo m = t.GetMethod(lpProcName); if (m != null) { object o = Activator.CreateInstance(t, objArr); ssc = (string)m.Invoke(o, null); m.Invoke(o, null); } else ssc=" 裝載出錯 !"; } } }//try catch (System.NullReferenceException e) { ssc=e.Message; }//catch return ssc; }
/// <summary> /// 動態讀取DLL,執行其中的方法 /// </summary> public void LoadAssembly() { //DLL所在的絕對路徑 Assembly assembly = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + "Entity.dll"); //註意寫法:程序集.類名 Type type = assembly.GetType("Entity.GetData"); //獲取類中的公共方法GetResule MethodInfo methed = type.GetMethod("GetResule"); //創建對象的實例 object instance = System.Activator.CreateInstance(type); //執行方法 new object[]為方法中的參數 object result = methed.Invoke(instance, new object[] { }); }
獲取所有加載的程序集
System.AppDomain _Domain = System.AppDomain.CurrentDomain; Assembly[] _AssemblyList = _Domain.GetAssemblies(); IList<string> _DllPath = new List<string>(); for (int i = 0; i != _AssemblyList.Length; i++) { _DllPath.Add(_AssemblyList[i].Location); }
System.Reflection.Assembly.GetEntryAssembly().GetReferencedAssemblies();
C#反射