C#继承的事件 [英] C# event inheritance

查看:146
本文介绍了C#继承的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    class One
    {
        public delegate void del(object o);
        public event del SomethingChanged;

        int x;
        public int X
        {
            get { return x; }
            set { x = value; OnSomethingChanged(this); }
        }

        protected void OnSomethingChanged(object o)
        {
            if (SomethingChanged != null)
                SomethingChanged(o);
        }
    }

    class Two: One
    {
        public void ChangeSomething()
        {
            //if (SomethingChanged != null)
            //    SomethingChanged(this);
            OnSomethingChanged(this);
        }
    }

    static void Main(string[] args)
    {
        One one = new One();
        Console.WriteLine(one.X);
        one.SomethingChanged += new One.del(one_SomethingChanged);
        one.X = 5;
    }

    static void one_SomethingChanged(object o)
    {
        Console.WriteLine(((One)o).X);
    }

有2类 - 一,二,二是的一个后代。有一个在一(SomethingChanged)类中声明事件,它是由一类和类双触发。但是看看Two.ChangeSomething - 它通过调用基类的方法会引发事件。但是,如果我尝试调用事件使用原始代码像

There are 2 classes - One and Two, Two is descendant of One. There is event declared in class One(SomethingChanged) and it is triggered by class One and class Two. But take a look at Two.ChangeSomething - it raises event by invoking base class's method. However if I try to invoke event using raw code like


if (SomethingChanged != null)
    SomethingChanged(this);



我收到编译器错误说

I'm getting compiler error saying


The event 'One.SomethingChanged' can only appear on the left hand side of += or -= (except when used from within the type 'eventstest.Program.One')

所以,我只是好奇,为什么我不能用原代码两级筹集事件,但是当我调用相应功能的事件引发得到?

So I'm just curious why I can't use 'raw' code in class Two to raise event but when I invoke a corresponding function event gets raised?


发现了一些澄清一下:
C#:提高继承的事件

推荐答案

在声明使用事件在C#中的事件的文章中,生成的IL实际上包含两个相应的元件:一个私人代表场和具有相同的可见性声明的事件的事件的访问。该事件访问不能被用来触发事件。它仅用于订阅和退订的通知。你的 SomethingChanged(本)代码使用的是私有字段来调用的委托,以及私人领域不能从外部类。

When you declare an event using the "event" keyword in C#, the generated IL actually contains two corresponding elements: a private delegate field and an event accessor with the same visibility as the declared event. The event accessor cannot be used to fire the event. It is only used to subscribe and unsubscribe from notifications. Your SomethingChanged(this) code is using the private field to invoke the delegate, and that private field is not available from outside the class.

这篇关于C#继承的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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