开发者

Field-like events and anonymous delegates

开发者 https://www.devze.com 2023-02-26 20:12 出处:网络
When name of a field-like event SomeNews is usedinside a class that declares this event, this name doesn\'t refer to the event itself, but to the anonymous private delegate D created by compiler, and

When name of a field-like event SomeNews is used inside a class that declares this event, this name doesn't refer to the event itself, but to the anonymous private delegate D created by compiler, and for that reason D can be invoked indirectly ( inside MyClass ) via SomeNews();

class MyClass
{ 
        public event MyDelegate SomeNews;
           ...
}

But if instead MyClass declares an event SomeNews by also specifying add and remove accessors:

class MyClass
{ 
        private delegate MyDelegate _someNews;
        public event MyDelegate SomeNews
        {
            add
            {
                _someNews += value;
            }

            remove
            {
           开发者_运维问答     _ someNews -= value;
            }
        }

        ...
}

does then even inside MyClass the name SomeNews refer to the event itself and not to the underlying delegate _someNews? I'm assuming this since trying to invoke _someNews delegate via SomeNews() will cause a compile-time error saying "SomeNews event can only appear on the left hand side of += or -="

thanx


It seems like you've answered your own question. Yes, when using full-bodied event syntax, referring to the event within the declaring class is no different than referring to it in any other class. This is because, like properties, the compiler has no idea what you're actually doing within the add and remove blocks.

There's nothing that says that you have to create a simple event that just adds and removes the value from an underlying delegate, or that you have to do anything with the supplied value at all. Because of this, it's not possible to "invoke" the event by simply calling it in code, since the compiler has no idea how to invoke the event.

0

精彩评论

暂无评论...
验证码 换一张
取 消