在反射中传递方法参数及注册事件的处理
最近在做一个插件形式的应用组件,用到了一些反射知识,所以写下这边篇文章来让自己以后更好的了解,也希望对一些做类似功能的朋友作参考。
类库代码:
using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; namespace Interface { public class Server { private Socket _serverSocket; private byte[] _byteData = new byte[1024]; public event EventHandler OnReceiveEvent; public void Listener() { try { _port = ConfigManager.AppSettings["Port"].Value; //创建socket,并绑定本地IP、port _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //得到本机IP,设置TCP端口号 var ip = new IPEndPoint(IPAddress.Any, Convert.ToInt32(_port)); //绑定网络地址 _serverSocket.Bind(ip); //开始接收client请求 var sender = new IPEndPoint(IPAddress.Any, 0); var remote = (EndPoint)(sender); _serverSocket.BeginReceiveFrom(_byteData, 0, _byteData.Length, SocketFlags.None, ref remote, OnReceive, remote); } catch (Exception ex) { Log.Error(ex.Message); } } private void OnReceive(IAsyncResult ar) { string str = "Hello"; if (OnReceiveEvent != null) OnReceiveEvent(str, null); } }
反射调用方法:
public void Listener() { try { //加载程序集(dll文件地址),使用Assembly类 Assembly assembly = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "Interface.dll"); //获取类型,参数(名称空间+类) Type type = assembly.GetType("Interface.Server"); //创建该对象的实例,object类型,参数(名称空间+类 object instance = assembly.CreateInstance("Interface.Server"); MethodInfo method = type.GetMethod("Listener"); //方法的名称 EventInfo eventinfo = type.GetEvent("OnReceiveEvent"); // 为事件动态绑定处理程序 if (eventinfo != null) eventinfo.AddEventHandler(instance, new EventHandler(OnReceive)); method.Invoke(instance, null); } catch (Exception ex) { MessageBox.Show(ex.Message); } } public void OnReceive(object sender, EventArgs e) { lbLogs.Items.Add("Server receive: " + sender); }