我对 c# 中的事件完全陌生,这就是我想做的:
我有两种方法:
OpenPage1();
OpenPage2();
当调用这些方法中的任何一个时,我想要调用名为 PerformSomeTask()
的第三个方法。
我相信这可以通过事件处理来完成。谁能告诉我该怎么做?
最佳答案
您在类里面所要做的就是添加一个具有正确事件处理程序的事件(在您的示例中为 Action)。 eventHandler 应该对应于将订阅此事件的方法。 然后从 openPage 方法触发事件。 如果没有人订阅此事件,您必须检查是否为 null。
public class Foo
{
public event Action theEvent;
public void OpenPage1()
{
if (theEvent != null)
theEvent();
}
public void OpenPage2()
{
if (theEvent != null)
theEvent();
}
}
public class Bar
{
public int Counter { get; set; }
public void PerformSomeTask()
{
Counter++;
}
}
这里有一个测试,您可以运行以查看所有内容:
[TestMethod]
public void TestMethod1()
{
var foo = new Foo();
var bar = new Bar();
foo.theEvent += bar.PerformSomeTask;
foo.OpenPage1();
foo.OpenPage2();
Assert.AreEqual(2, bar.Counter);
}
关于c# - 如何在 C# 中使用事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29251982/