C# 反射相关的东西

时间:2021-01-26 11:55:46
 public class PlugingManager
    {
        //插件装载器
        public ArrayList Plugins = new ArrayList();
        //插件FullName
        public ArrayList PlugFullName = new ArrayList();
        //插件类型
        public ArrayList PlugTypes = new ArrayList();

#region 构造函数
        /// <summary>
        /// PlugingManager插件加载
        /// </summary>
        /// <param name="plugspath">插件所在目录必须是运行目录中的文件夹</param>
        /// <param name="StartsWith">加载指定插件(插件包含的名称)</param>
        /// <param name="InterfaceName">插件接口名称</param>
        public PlugingManager(string plugspath,string StartsWith,string InterfaceName)
        {
            //获取插件目录(plugins)下所有文件
            string[] files = Directory.GetFiles(Application.StartupPath + @"\\" + plugspath);
           
            foreach (string file in files)
            {
                if (file.ToUpper().EndsWith(StartsWith.ToUpper()))
                {
                    try
                    {
                        //Assembly ab = Assembly.LoadFrom(file);
                        Assembly ab = null;

//先将插件拷贝到内存缓冲
                        byte[] addinStream = null;
                        using(FileStream input = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            BinaryReader reader = new BinaryReader(input);
                            addinStream = reader.ReadBytes((int) input.Length);

}
                        ab = Assembly.Load(addinStream); //加载内存中的Dll
                        Type[] types = ab.GetTypes();
                        foreach (Type t in types)
                        {
                            if (t.GetInterface(InterfaceName) != null)
                            {
                                Plugins.Add(ab.CreateInstance(t.FullName));
                                PlugFullName.Add(t.FullName);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }
        #endregion
    }

C# 反射相关的东西

PlugingManager plug = new PlugingManager("Plugs", "Garden.Plugs.dll", "IPlug");

var win = plug.Plugins.ToArray().FirstOrDefault(m => ((Type)m.GetType()).Name.ToLower() == this.Tag.ToString().ToLower());
            MethodInfo OnShowDlg = ((Type)win.GetType()).GetMethod("ShowSelf");
            Form cl = (Form)OnShowDlg.Invoke(win, null);
            cl.WindowState = FormWindowState.Maximized;
            cl.MdiParent = this;
            cl.Show();
            foreach (object obj in plug.Plugins)
            {

Type t = obj.GetType();
                MethodInfo OnShowDlg = t.GetMethod("ShowSelf");
                Control cl = (Control)OnShowDlg.Invoke(obj, null);

Control con = GetControlFromForm(t.Name, this);
                if (con != null)
                {
                    con.Controls.Add(cl);
                    cl.Dock = DockStyle.Fill;
                    isbreak = false;
                    con = null;
                }

C# 反射相关的东西

}

上面是从内存中生成对象

//获取程序集 
            Assembly assembly = Assembly.Load("环环环环环");
            Assembly assembly2 = Assembly.LoadFrom("环环环环环.dll");             //从程序集中获取指定对象类型;
            Type type = assembly.GetType("环环环环环.User");             //使用Activator创建实例(无参数构造函数)
            var user1 = Activator.CreateInstance(type);
            //使用Activator创建实例(带参数构造函数)
            var user2 = Activator.CreateInstance(type, "薄暮");             //使用Assembly创建实例(无参数构造函数)
            var user3 = assembly.CreateInstance("环环环环环.User");             //反射无参构造函数
            ConstructorInfo constructor1 = type.GetConstructor(new Type[] {});
            var user4 = constructor1.Invoke(new object[] { });             //反射有参构造函数 
            ConstructorInfo constructor2 = type.GetConstructor(new Type[] { typeof(string) });
            var user5 = constructor2.Invoke(new object[] { "薄暮" });             //调用public函数(无参数)
            type.InvokeMember("PublicShow",
                              BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, user1,
                              null);             //调用public函数(带参数)
            string returnValue =
                type.InvokeMember("GetString",
                                  BindingFlags.InvokeMethod | BindingFlags.OptionalParamBinding, null, user1,
                                  new object[] { "薄暮" }) as string;             // 调用静态方法       
            string returnValue2 =
                type.InvokeMember("StaticMethod", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static,
                                  null, null, new object[] {}) as string;             // 调用私有方法 .       
            type.InvokeMember("PrivateShow",
                              BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, user1,
                              new object[] {});             //反射属性
            var Name =
                type.InvokeMember("Name", BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance, null,
                                  user1, new object[] {}) as string;             //设置属性(设置Name属性为"新属性")
            type.InvokeMember("Name", BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance, null,
                                  user1, new object[] {"新属性"});             //反射字段
            string Field =
                type.InvokeMember("Field", BindingFlags.GetField | BindingFlags.Public | BindingFlags.Instance, null,
                                  user1, new object[] {}) as string;             //设置字段(设置Field字段为"新字段")
            type.InvokeMember("Field", BindingFlags.SetField | BindingFlags.Public | BindingFlags.Instance, null,
                                  user1, new object[] { "新字段" });

这是标准的用法,还挺好玩的吧