最近在作一個插件形式的應用組件,用到了一些反射知識,因此寫下這邊篇文章來讓本身之後更好的瞭解,也但願對一些作相似功能的朋友做參考。網絡
類庫代碼:socket
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); } }
反射調用方法:spa
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); }