Show/Hide Toolbars

XSharp

Navigation: X# 文档 > X# 入门 > 新的语言特性

EVENT(Add 和 Remove)))

Scroll Prev Top Next More

 

XSharp 现在支持扩展的 "EVENT" 语法。既支持单行语法,也支持多行语法:

旧语法

[Attributes] [Modifiers] EVENT [<ExplicitInterface>.] <Id> AS <Type>    // 旧语法

带有明确表达式的单行语法

[Attributes] [Modifiers] EVENT [<ExplicitInterface>.] <Id> AS <Type>   [ADD <ExpressionList] [REMOVE <ExpressionList]   // 单行

带有明确表达式的多行语法

[Attributes] [Modifiers] EVENT [<ExplicitInterface>.] <Id> AS <Type>     // 多行
 
ADD
   <Statements>
END [ADD]
REMOVE
   <Statements>
END [REMOVE]
END [EVENT]

 

示例

USING System.Collections.Generic
FUNCTION Start AS VOID
  LOCAL e AS EventsExample
   e := EventsExample{}
   e:Event1 += TestClass.DelegateMethod
   e:Event1 += TestClass.DelegateMethod
   e:Event1 -= TestClass.DelegateMethod   // 增加 2 个,删除 1 个,应调用一次
   e:Event2 += TestClass.DelegateMethod
   e:Event2 += TestClass.DelegateMethod
   e:Event2 -= TestClass.DelegateMethod // 增加 2 个,删除 1 个,应调用一次
   e:Event3 += TestClass.DelegateMethod
   e:RaiseEvent1("这是一个通过多行事件定义进行的测试")
   e:RaiseEvent2("这是一个通过单行事件定义进行的测试")
   e:RaiseEvent3("这是一个通过旧式事件定义进行的测试")
   Console.WriteLine("任意键退出")
   Console.ReadLine()
 
 
DELEGATE EventHandler (s AS STRING) AS VOID
 
CLASS TestClass
  STATIC METHOD DelegateMethod(s AS STRING ) AS VOID
       Console.WriteLine( s)
END CLASS
 
 
CLASS EventsExample
  PRIVATE eventsTable AS Dictionary<STRING, System.Delegate>
  PRIVATE CONST sEvent1 := "Event1" AS STRING
  PRIVATE CONST sEvent2 := "Event2" AS STRING
   CONSTRUCTOR()
       eventsTable := Dictionary<STRING, System.Delegate>{}
       eventsTable:Add(sEvent1,NULL_OBJECT)
       eventsTable:Add(sEvent2,NULL_OBJECT)
 
  // 多行定义
  EVENT Event1 AS EventHandler
       ADD
          BEGIN LOCK eventsTable
               eventsTable[sEvent1] := ((EventHandler) eventsTable[sEvent1]) + value
          END LOCK
           Console.WriteLine(__ENTITY__ + " "+value:ToString())
      END
       REMOVE
          BEGIN LOCK eventsTable
               eventsTable[sEvent1] := ((EventHandler) eventsTable[sEvent1]) - value
          END LOCK
           Console.WriteLine(__ENTITY__+ " "+value:ToString())
      END
  END EVENT
 
 
  // 在多行上用分号断行,进行单行定义,以便更好地阅读!
  EVENT Event2 AS EventHandler  ;
       ADD     eventsTable[sEvent2] := ((EventHandler) eventsTable[sEvent2]) + value ;
       REMOVE  eventsTable[sEvent2] := ((EventHandler) eventsTable[sEvent2]) - value
 
  // 旧风格的定义
  EVENT Event3 AS EventHandler
 
  METHOD RaiseEvent1(s AS STRING) AS VOID
      VAR handler := (EventHandler) eventsTable[sEvent1]
      IF handler != NULL
           handler(s)
      ENDIF
 
  METHOD RaiseEvent2(s AS STRING) AS VOID
      VAR handler := (EventHandler) eventsTable[sEvent2]
      IF handler != NULL
           handler(s)
      ENDIF
 
  METHOD RaiseEvent3(s AS STRING) AS VOID
      IF SELF:Event3 != NULL
           Event3(s)
      ENDIF
END CLASS