111,129
社区成员
发帖
与我相关
我的任务
分享
public static class ActionHelper
{
public static Action TestAction;
}
public class ReceiveA
{
public ReceiveA()
{
ActionHelper.TestAction = TestAction;
}
private void TestAction()
{
MessageBox.Show("A");
}
}
public class ReceiveB
{
public ReceiveB()
{
ActionHelper.TestAction = TestAction;
}
private void TestAction()
{
MessageBox.Show("B");
}
}
private void ActonTestBtn_Click(object sender, EventArgs e)
{
ReceiveA receiveA = new ReceiveA();
ReceiveB receiveB = new ReceiveB();
if (ActionHelper.TestAction != null)
{
ActionHelper.TestAction();
}
}
public class ReceiveA : IDisposable
{
public ReceiveA()
{
ActionHelper.TestAction += TestAction;
}
public void Dispose()
{
ActionHelper.TestAction -= TestAction;
}
........
并且要求显式用你的代码来调用 A 类对象实例的 Dispose 方法,例如放到 using(){...} 结构中。否则,可能就根本无法真正让 GC 去回收此类对象实例,因为 public static Action TestAction;总是引用着它,无法释放。
反过来,也说明你使用 static Action TestAction 这个设计是有问题的、找麻烦的。
ActionHelper.TestAction += TestAction;
就是如此。
但是,你从中也就能看到了,任何一个外部类都能胡乱修改它。例如 A 使用了 +=,而B 还是原来的写法,则 A 中正常的 += 就代码自欺欺人地(而不是明明白白地)篡改了。所以实际上这通常写为public static class ActionHelper
{
public static event Action TestAction;
public static void Go()
{
if (ActionHelper.TestAction != null)
{
ActionHelper.TestAction();
}
}
}ReceiveA receiveA = new ReceiveA();
ReceiveB receiveB = new ReceiveB();
ActionHelper.Go();
这样,可以防止 ActionHelper 类以外的代码去(不小心)篡改它。