C#中常用作event的delegate 函数
通用用法,用户创建对象,注册事件,表示事件发生时的响应
server = new AsyncServer(10001, new byte[] { 0x0D}); server.DataReceived += (s, e) => {
... };
常用event的委托函数说明和使用
1
public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);
使用例子:在某个类里面
public event EventHandler<TcpClientKickedEventArgs> ClientKicked; //事件触发 if(ClientKicked!=null) { ClientKicked(this, new TcpClientKickedEventArgs(client.client)); }
题外话:TcpClientKickedEventArgs的定义
//题外话 public class TcpClientKickedEventArgs:EventArgs { public TcpClientKickedEventArgs(TcpClient tcpClient) { this.TcpClient = tcpClient; } public TcpClient TcpClient { get; private set; } }
2
public delegate void EventHandler(object sender, EventArgs e);
某个类里面
public class TestClass { public event EventHandler TestEvent; public void RaiseEvent() { //某个时刻事件触发 TestEvent?.Invoke(this, null); } }
注册使用
TestClass t = new TestClass(); t.TestEvent += T_TestEvent; ............. private void T_TestEvent(object sender, EventArgs e) { MessageBox.Show("HI"); }
其余
public delegate void Action(); public delegate void Action<in T1, in T2, in T3>(T1 arg1, T2 arg2, T3 arg3); public delegate void Action<in T1, in T2>(T1 arg1, T2 arg2); public delegate void Action<in T>(T obj);
public delegate TResult Func<out TResult>(); public delegate TResult Func<in T, out TResult>(T arg); public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);