时间:: accessing parent class's events not possible?

标签 c# events inheritance

以前从来没有遇到过这个。这是示例:

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/

相关文章:

Javascript 原型(prototype)继承 : problem when parent and child receive same object as argument?

c# - WAV 文件修剪和添加静音

c# - 在 C# 中将金额转换为卢比和 paise 中的单词格式

c# - 如何在 NUnit 3 中使用测试套件

c# - 在 C# MySqlCommand.CommandText 中使用 SQL 关键字

c++ - 从基类构造函数构造派生类对象

Java 事件、处理程序和监听器问题

email - 事件跟踪,尤其是在电子邮件上的事件谷歌分析不起作用

jquery - 如何从特定命名空间解除所有 jQuery 事件的绑定(bind)?

css - 两个连续调用的样式表中的第二个能否覆盖第一个中定义的所有样式?