c#:访问父类的事件是不可能的? [英] c# : accessing parent class's events not possible?

查看:762
本文介绍了c#:访问父类的事件是不可能的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  using System; 

命名空间测试
{
public class Test
{
public event Action ActionRequired;


public class ChildTest:Test
{
public void DoSomething()
{
if(this.ActionRequired!= null)
this.ActionRequired();
}
}
}

这不行,这个错误是我只能从基类访问事件。



这样做并不困难(将一个受保护的方法添加到同时检查调用的基类)的事件,并从儿童课程中调用该方法),但我真的不知道这个限制背后的意思是什么?



干杯,



Sebi

解决方案

您无法从定义的类外调用事件。但是,你不需要;只要按照惯用的方式也声明一个受保护的方法来触发所述事件。

  class Whatever 
{
公共事件EventHandler Foo;

protected virtual void OnFoo(EventArgs e)
{
EventHandler del = Foo;
if(del!= null)
{
del(this,e);
}
}
}

现在的类的后代无论可以通过调用OnFoo()并传递相应的EventArgs对象来触发事件。



编辑:关于为什么这是行为,Jon Skeet解释得很好另一个线程(这也意味着这个问题是重复的,所以投票关闭):


当你声明一个类似公共类的事件,编译器创建一个公共事件和一个私有字段。在同一个类(或嵌套类)中,您可以直接在字段中获得。调用所有的处理程序。从其他课程中,您只能看到事件,只允许订阅和取消订阅。



never came across this before. Here's the sample:

using System;

namespace Testing
{
    public class Test
    {
        public event Action ActionRequired;
    }

    public class ChildTest : Test
    {
        public void DoSomething()
        {
            if (this.ActionRequired != null)
                this.ActionRequired();
        }
    }
}

This won't work, the error being I can only access the event from the base class.

It's not difficult to sail around (add a protected method to the base class that does both check an invocation of the event and call that method from the child classes), but I really wonder what's the idea behind this restriction?

Cheers,

Sebi

解决方案

You cannot invoke events from outside of the class within which they were defined. However, you don't need to; just follow the idiomatic patter of also declaring a protected method to fire said event.

class Whatever
{
    public event EventHandler Foo;

    protected virtual void OnFoo( EventArgs e )
    {
        EventHandler del = Foo;
        if( del != null )
        {
            del( this, e );
        }
    }
}

Now descendants of class "Whatever" can fire the event by calling OnFoo() and passing in the appropriate EventArgs object.

EDIT: In regards to why this is the behavior, Jon Skeet explained it well in another thread (which also means that this question is a duplicate, so voting to close):

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.

这篇关于c#:访问父类的事件是不可能的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆