Skip to main content
 首页 » 编程设计

c#之Roslyn 中事件的 “raise” 访问器是什么

2024年02月06日18dyllove98

罗斯林的 IEventSymbol提供对事件声明的所有相关部分的便捷访问。虽然 AddMethod 和 RemoveMethod 足够简单易懂,但我不确定 RaiseMethod 应该是什么。文档也有点解析。

C# 规范仅提及为事件添加和删除访问器。这可能是其他 CLR 语言允许指定的内容吗?

请您参考如下方法:

我找到了 this在 Roslyn 源代码中:

internal abstract partial class EventSymbol : Symbol, IEventSymbol 
{ 
    ... 
 
    IMethodSymbol IEventSymbol.RaiseMethod 
    { 
        get 
        { 
            // C# doesn't have raise methods for events. 
            return null; 
        } 
    } 
 
    ... 
} 

看起来它实际上适用于 Visual Basic。 :

An event is like a message announcing that something important has occurred. The act of broadcasting the message is called raising the event. In Visual Basic, you raise events with the RaiseEvent statement, as in the following example:

RaiseEvent AnEvent(EventNumber)

Events must be raised within the scope of the class, module, or structure where they are declared. For example, a derived class cannot raise events inherited from a base class.

在 Roslyn source for VB 中查找,很多对该RaiseMethod 属性的引用。

VB 规范在第 9.4.1 节中明确提到了 RaiseEvent 访问器自定义事件:

Custom events are declared in the same way that events that specify a delegate type are declared, with the exception that the keyword Custom must precede the Event keyword. A custom event declaration contains three declarations: an AddHandler declaration, a RemoveHandler declaration and a RaiseEvent declaration. None of the declarations can have any modifiers, although they can have attributes. For example:

Class Test 
    Private Handlers As EventHandler 
 
    Public Custom Event TestEvent As EventHandler 
        AddHandler(value As EventHandler) 
            Handlers = CType([Delegate].Combine(Handlers, value), _ 
                EventHandler) 
        End AddHandler 
 
        RemoveHandler(value as EventHandler) 
            Handlers = CType([Delegate].Remove(Handlers, value), _ 
                EventHandler) 
        End RemoveHandler 
 
        RaiseEvent(sender As Object, e As EventArgs) 
            Dim TempHandlers As EventHandler = Handlers 
 
            If TempHandlers IsNot Nothing Then 
                TempHandlers(sender, e) 
            End If 
        End RaiseEvent 
    End Event 
End Class