我的事件处理程序代码正确吗?将数据从子节点传递到父节点

本文关键字:子节点 数据 父节点 程序 事件处理 代码 我的 | 更新日期: 2023-09-27 18:13:37

我创建了一个小示例项目来尝试理解事件。我想最终实现这些类型的事件在我未来的项目,特别是当从子表单传递数据到父表单…我也经常这么做有人告诉我,要避免耦合,最好的方法是使用事件。

我的代码是否低于正确/传统的方式来实现这一点?

// 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类中使用方法,但它不允许我调用公共方法。像我这样访问属性是惯例吗?

谢谢

我的事件处理程序代码正确吗?将数据从子节点传递到父节点

1)消息框未被调用,因为您正在实例化类之后订阅事件,因此方法onAccountRegister()将不会被调用

registerUserAccount registerAccount = new registerUserAccount();
registerAccount.onAccountCreated += onAccountRegister; 

顺便说一句,

我建议重命名事件和事件处理程序方法:

  • onAccountCreatedAccountCreated
  • onAccountRegisterAccountCreatedHandler,因为您正在订阅AccountCreated事件而不是AccountRegister