C# 触发另一个类的事件时通知
我有C# 触发另一个类的事件时通知,c#,events,event-handling,C#,Events,Event Handling,我有 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 MyMet
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类中删除事件 看看
您需要在“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
}
....
您需要三件事(在代码中用注释标记):
Thx伙计们,所有答案+1到allDunno为什么要搜索一个C#event示例如此清晰和简单,只是为了交流两个类?经过几个小时的搜索终于。。。我想哭,非常感谢。@Konayuki:非常同意。我一直在寻找一个简单的例子,就是这样。(at)DaveBish:干得好——简单有效。
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() { }
}