C#反射
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, string Namespace, 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();