【发布时间】:2016-10-20 12:56:08
【问题描述】:
我还是 C# 和编程的新手。我已经使用过 WPF 并寻找了一种套接字实践。而且我只是不明白 eventHandlers 中存在第二个参数的原因。
我正在尝试制作一个异步服务器。但是在视频中,程序员已将自定义 eventArgs 添加到对象本身并将它们添加到 eventHandler 中。为了让事情更清楚一点,代码的一部分:
接收数据类的缓冲区
class DataReceivedEventArgs : EventArgs
{
public const int BufferSize = 1024;
public byte[] BufferBytes;
public int ToReceive;
public MemoryStream BufferStream;
// Constructor for this
public DataReceivedEventArgs(int toReceive)...
// Dispose function for this
public void Dispose()...
// Close function for stream
private void Close()...
}
客户端类
class Client
{
private byte[] lenBufferBytes;
private DataReceivedEventArgs receiveBuffer;
private Socket socket;
public IPEndPoint EndPoint...
// Constructor for this
public Client(Socket socket)
{
this.socket = socket;
this.lenBufferBytes = new byte[4];
}
// Events
public event EventHandler Disconnected;
public event EventHandler<DataReceivedEventArgs> DataReceived;
// Event Invokers
protected virtual void OnDisconnected()
{
Disconnected?.Invoke(this, EventArgs.Empty);
}
protected virtual void OnDataReceived(DataReceivedEventArgs e)
{
DataReceived?.Invoke(this, e);
}
}
所以我的问题是:
1.为什么你需要通过两次相同的事情?
和
2。如果您可以将所有内容存储在对象中并仅更改对象类而无需在需要添加新参数时破坏代码,为什么还需要 eventArgs?
【问题讨论】:
标签: c# wpf sockets events server