zoukankan      html  css  js  c++  java
  • 学习反射例子,调用DLL窗体及方法

    创建类库,并添加新窗体,加入以下方法

    public static string setText(string str)
    {
        return str;
    }

    编译后把生成的DLL文件放入新项目的bin目录,新项目需要using System.Reflection窗口放入2个button,并添加实现

    //通过反射打开Dll窗体
    private void button1_Click(object sender, EventArgs e)
    {
        //dll命名空间名
        string dllName = "DllDemo";
        //dll类名
        string dllClassName = "DllDemo.Form1";
        //载入并创建实例转为Form类型
        Form frm = Assembly.Load(dllName).CreateInstance(dllClassName) as Form;
        frm.ShowDialog();
    }
    //通过反射调用Dll中的方法
    private void button2_Click(object sender, EventArgs e)
    {
        //dll文件路径
        string dllName = "DllDemo";
        //dll类名
        string dllClassName = "DllDemo.Form1";
        //加载dll文件
        var assembly = Assembly.Load(dllName);
        //获取类
        Type type = assembly.GetType(dllClassName);
        //创建该类型的实例
        object obj = Activator.CreateInstance(type);
        //获取该类的方法
        string str = type.InvokeMember("setText", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, new object[] { textBox1.Text }).ToString();
        MessageBox.Show(str);
    
        //缩写
        string returnStr = Assembly.Load(dllName)
                          .GetType(dllClassName)
                          .InvokeMember(
                                        "setText"
                                        , BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static
                                        , null
                                        , null
                                        , new object[] { textBox1.Text }  //传入方法参数
                                        )
                          .ToString();
        MessageBox.Show(returnStr);
    
    }
  • 相关阅读:
    OC中ARC forbids explicit message send of release错误
    OC中内存管理(转)
    [题解]数学期望_luogu_P1850_换教室
    [题解](单调队列)luogu_P2216_BZOJ_1047 理想的正方形
    [题解]luogu_AT1224_JOIOJI
    [题解]区间dp_luogu_P3147 262144
    [筆記]歐拉路
    [題解/狀壓dp]POJ_2411_Mondriaan's dream
    [題解]luogu_P1854 花店櫥窗佈置
    [題解]luogu_P1052 過河
  • 原文地址:https://www.cnblogs.com/liessay/p/12876553.html
Copyright © 2011-2022 走看看