0
任何使這個工作代碼更簡單的方法,即代理{}?另一個類.NET2中的WinForm事件簡化代理
public partial class Form1 : Form
{
private CodeDevice codeDevice;
public Form1()
{
InitializeComponent();
codeDevice = new CodeDevice();
//subscribe to CodeDevice.ConnectionSuccessEvent and call Form1.SetupDeviceForConnectionSuccessSate when it fires
codeDevice.ConnectionSuccessEvent += new EventHandler(SetupDeviceForConnectionSuccessState);
}
private void SetupDeviceForConnectionSuccessState(object sender, EventArgs args)
{
MessageBox.Show("It worked");
}
private void button1_Click(object sender, EventArgs e)
{
codeDevice.test();
}
}
public class CodeDevice
{
public event EventHandler ConnectionSuccessEvent = delegate { };
public void ConnectionSuccess()
{
ConnectionSuccessEvent(this, new EventArgs());
}
public void test()
{
System.Threading.Thread.Sleep(1000);
ConnectionSuccess();
}
}
WinForm event subscription to another class
How to subscribe to other class' events in c#?
謝謝@Ben - 剛剛試過,因爲我沒有使用對象,而不是ARGS另一個是ConnectionSuccess(NULL,NULL)。不過現在會像上面那樣熱衷於。 –
ConnectionSuccess(null,null)的問題是您添加了發件人或eventargs永遠不會被引用的假設。另一個開發者可能會寫一個方法來描述這個事件,並使用這些參數,然後引起一個空引用異常。 'ConnectionSuccessEvent(this,new EventArgs());'或'ConnectionSuccessEvent(this,EventArgs.Empty);'更好。 –