我有
class A
{
B b;
//call this Method when b.Button_click or b.someMethod is launched
private void MyMethod()
{
}
??
}
Class B
{
//here i.e. a button is pressed and in Class A
//i want to call also MyMethod() in Class A after the button is pressed
private void Button_Click(object o, EventArgs s)
{
SomeMethod();
}
public void SomeMethod()
{
}
??
}
类 A 具有类 B 的实例。
如何做到这一点?
您需要在类"B"上声明一个公共事件 - 并让类"A"订阅它:
像这样:
class B
{
//A public event for listeners to subscribe to
public event EventHandler SomethingHappened;
private void Button_Click(object o, EventArgs s)
{
//Fire the event - notifying all subscribers
if(SomethingHappened != null)
SomethingHappened(this, null);
}
....
class A
{
//Where B is used - subscribe to it's public event
public A()
{
B objectToSubscribeTo = new B();
objectToSubscribeTo.SomethingHappened += HandleSomethingHappening;
}
public void HandleSomethingHappening(object sender, EventArgs e)
{
//Do something here
}
....
你需要三件事(由代码中的注释标记):
- 声明类 B 中的事件
- 当发生某些事情时,在类 B 中引发事件(在您的情况下 - Button_Click执行的事件处理程序)。请记住,您需要验证是否存在任何订阅者。否则,您将在引发事件时获得 NullReferenceException。
- 订阅 B 类事件。你需要有类 B 的实例,即使你想订阅它(另一个选项 - 静态事件,但这些事件将由类 B 的所有实例引发)。
法典:
class A
{
B b;
public A(B b)
{
this.b = b;
// subscribe to event
b.SomethingHappened += MyMethod;
}
private void MyMethod() { }
}
class B
{
// declare event
public event Action SomethingHappened;
private void Button_Click(object o, EventArgs s)
{
// raise event
if (SomethingHappened != null)
SomethingHappened();
SomeMethod();
}
public void SomeMethod() { }
}
看看从 B 类中获取事件
看看
引发事件
处理和引发事件
如何:引发和使用事件