0
我創建了一個小示例項目來嘗試理解事件。我希望最終在將來的項目中實現這些類型的事件,尤其是將數據從子表單傳遞到父表單時...這是我做的很多事情。我被告知最好的方式來做到這一點,以避免耦合,就是使用事件。我的事件處理程序代碼是否正確?將數據從子項傳遞給父項
是我的代碼低於正確/常規的方式來實現這一目標?
// Subscriber
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
registerUserAccount registerAccount = new registerUserAccount();
registerAccount.onAccountCreated += onAccountRegister;
registerAccount.registerAccount();
}
public void onAccountRegister(object sender, AccountCreatedEventArgs e)
{
MessageBox.Show(e.username + " - " + e.password);
}
}
public delegate void accountCreatedEventHandler(object sender, AccountCreatedEventArgs e);
// Publisher
public class registerUserAccount
{
public event accountCreatedEventHandler onAccountCreated;
public registerUserAccount()
{
}
public void registerAccount()
{
// Register account code would go here
AccountCreatedEventArgs e = new AccountCreatedEventArgs("user93248", "0Po8*(Sj4");
onAccountCreated(this, e);
}
}
// Custom Event Args
public class AccountCreatedEventArgs : EventArgs
{
public String username;
public String password;
public AccountCreatedEventArgs(String _username, String _password)
{
this.username = _username;
this.password = _password;
}
}
注意:上面的代碼放在相同的命名空間中,僅供演示和測試。
幾個問題太多:
1)我想有registerUserAccount構造函數調用registerAccount方法,但由於某些原因,它沒有給我消息框。我認爲這是因爲registerAccount方法在類訂閱以監聽事件之前調用?
2)我試圖在EventArgs類中使用方法,但它不允許我調用公共方法。訪問像我這樣的屬性是否約定?
感謝
感謝@sll。在我調用ChildForm.Show()的真實情況下,我將如何解決我的第一個問題?由於ChildForm正在處理註冊,並且如果我在ChildForm.Show()之後訂閱事件,事件將永遠不會被正確拾取? –
@Sian Jakey Ellis:對,但爲什麼不在Show()調用之前訂閱? – sll
你說得對。對不起,我還沒有喝過早晨的咖啡:) –