C# 当来自另一个类的事件被触发时通知
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13856869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Notify when event from another class is triggered
提问by Gobliins
I have
我有
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()
{
}
??
}
Class A has a instance of Class B.
A 类有 B 类的一个实例。
How can this be done?
如何才能做到这一点?
采纳答案by Dave Bish
You'll need to declare a public event on class 'B' - and have class 'A' subscribe to it:
您需要在“B”类上声明一个公共事件 - 并让“A”类订阅它:
Something like this:
像这样的东西:
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
}
....
回答by Adriaan Stander
Have a look at rasing an event from Class B
看看从 B 类引发事件
Have a look at
看一下
回答by Sergey Berezovskiy
You need three things (which is marked by comments in code):
您需要三样东西(在代码中用注释标记):
- Declare eventin class B
- Raise event in class B when something happened (in your case - Button_Click event handler executed). Keep in mind that you need to verify if there are any subscribers exists. Otherwise you will get NullReferenceException on raising event.
- Subscribe to event of class B. You need to have instance of class B, which even you want to subscribe (another option - static events, but those events will be raised by all instances of class B).
- 在 B 类中声明事件
- 发生某些事情时在 B 类中引发事件(在您的情况下 - Button_Click 事件处理程序已执行)。请记住,您需要验证是否存在任何订阅者。否则,您将在引发事件时收到 NullReferenceException。
- 订阅类 B 的事件。您需要有类 B 的实例,即使您想订阅它(另一个选项 - 静态事件,但这些事件将由类 B 的所有实例引发)。
Code:
代码:
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() { }
}

