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
你说得对。对不起,我还没有喝过早晨的咖啡:) –