反射的常用用法

来源:互联网 发布:2015淘宝新店扶持时间 编辑:程序博客网 时间:2024/04/28 10:06

1.反射调用窗体
private void button1_Click(object sender, System.EventArgs e)
  {
   Assembly assm = Assembly.LoadFrom("e://WindowsApplication5.dll");
   Type TypeToLoad= assm.GetType("WindowsApplication5.Form1");
   
   object obj;
   obj = Activator.CreateInstance(TypeToLoad);
   Form formToShow = null;
   formToShow = (Form)obj;
   formToShow.Show();
  
  }
2
private void button1_Click(object sender, System.EventArgs e)
  {
   try
   {
    Type t = Type.GetType("WindowsTest.Form2");
    object obj = System.Activator.CreateInstance(t);
    MethodInfo mif = t.GetMethod("Show");
    mif.Invoke(obj,null);//or ((Form)obj).Show();
   }
   catch(Exception ex)
   {
    MessageBox.Show(ex.Message);
   }
  }
3
private void btnReflection_Click(object sender, System.EventArgs e)
  {
   try
   {
    Assembly assembly = Assembly.LoadFrom(@"D:/WindowsTest/WindowsTest/bin/Debug/MyClassLib.dll");
    Type typeload = assembly.GetType("MyClassLib.Class1");
    object obj = Activator.CreateInstance(typeload);
    //MethodInfo method = typeload.GetMethod("ShowMessage",new Type[]{typeof(string),typeof(int)});
    //method.Invoke(obj,new object[]{"2342",213});
    MethodInfo []methods = typeload.GetMethods();
    MethodInfo method = typeload.GetMethod("ShowMessage",Type.EmptyTypes);
    method.Invoke(obj,null);
    
    MessageBox.Show("Success!");
   }
   catch( Exception ex)
   {
    MessageBox.Show(ex.Message);
   }
  }

7.
例DLL 文件内容如下:

using System;
using System.Windows.Forms;

namespace ArLi.CommonPrj {
 public class ShowAboutBox {
  public static void ShowOn(Form fm) {
   MessageBox.Show("OK");
  }
 }
}

编译后文件名叫 AboutBox.dll

主程序里调用方法如下:

//定义文件名
FileInfo aBoxFile = new FileInfo(Path.Combine(Application.StartupPath,"AboutBox.dll"));

if (aBoxFile.Exists) { //如果存在
 try { //预防意外,比如不载不完整,非法DLL
  // 开始载入
  Assembly aBox = Assembly.LoadFrom(aBoxFile.FullName);
  Type[] _t = aBox.GetTypes(); //获得全部Type
  foreach (Type t in _t) { //遍历
   //如果发现名称空间和类名有相符的
   if (t.Namespace == "ArLi.CommonPrj" && t.Name == "ShowAboutBox") {
    //载入方法
    MethodInfo m = t.GetMethod("ShowOn");
    if (m != null) { //如果要载入的方法存在
     //创建实例
     object o = Activator.CreateInstance(t);
     //执行该方法,后面的this 是参数
     m.Invoke(o,new object[]{this});
    }
    else { //载入的方法不存在
     MessageBox.Show("File /"AboutBox.dll/" Invalid!/n/nMethod Error.");
    }
    return;
   }
  }
  MessageBox.Show("File /"AboutBox.dll/" Invalid!/n/nAssembly Name Error.");
 } //文件、命名空间、方法都相符,但执行该DLL 内容出错
 catch (System.NullReferenceException ex) {
  MessageBox.Show("File /"AboutBox.dll/" Invalid!");
 } //文件非正常DLL
 catch (Exception ex) {
  MessageBox.Show("File /"AboutBox.dll/" Error: /n/n" + ex.Message);
 }
}
else { //文件没找到
 MessageBox.Show("File /"AboutBox.dll/" Missing!");
}

原创粉丝点击