以前从来没有遇到过这个。这是示例:
using System;
namespace Testing
{
public class Test
{
public event Action ActionRequired;
}
public class ChildTest : Test
{
public void DoSomething()
{
if (this.ActionRequired != null)
this.ActionRequired();
}
}
}
这行不通,错误是我只能从基类访问事件。
这并不难(向基类添加一个 protected 方法,它既检查事件的调用又从子类调用该方法),但我真的很想知道这个限制背后的想法是什么?
干杯,
塞比
最佳答案
您不能从定义事件的类之外调用事件。但是,您不需要;只需遵循同样声明 protected 方法来触发所述事件的惯用模式即可。
class Whatever
{
public event EventHandler Foo;
protected virtual void OnFoo( EventArgs e )
{
EventHandler del = Foo;
if( del != null )
{
del( this, e );
}
}
}
现在类“Whatever”的后代可以通过调用 OnFoo() 并传入适当的 EventArgs 对象来触发事件。
编辑:关于为什么会出现这种行为,Jon Skeet 在另一个线程中解释得很好(这也意味着这个问题是重复的,所以投票结束):
When you declare a public field-like event, the compiler creates a public event, and a private field. Within the same class (or nested classes) you can get at the field directly, e.g. to invoke all the handlers. From other classes, you only see the event, which only allows subscription and unsubscription.
关于时间:: accessing parent class's events not possible?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4742214/