.NET EventHandlers - Generic or no?

后端 未结 9 1919
遇见更好的自我
遇见更好的自我 2020-12-03 13:53

Every time I start in deep in a C# project, I end up with lots of events that really just need to pass a single item. I stick with the EventHandler/Event

9条回答
  •  臣服心动
    2020-12-03 14:27

    To make generic event declaration easier, I created a couple of code snippets for it. To use them:

    • Copy the whole snippet.
    • Paste it in a text file (e.g. in Notepad).
    • Save the file with a .snippet extension.
    • Put the .snippet file in your appropriate snippet directory, such as:

    Visual Studio 2008\Code Snippets\Visual C#\My Code Snippets

    Here's one that uses a custom EventArgs class with one property:

    
    
      
        
    Generic event with one type/argument. ev1Generic Code snippet for event handler and On method Ryan Lundy Expansion
    type Type of the property in the EventArgs subclass. propertyType argName Name of the argument in the EventArgs subclass constructor. propertyName propertyName Name of the property in the EventArgs subclass. PropertyName eventName Name of the event NameOfEvent $eventName$; protected virtual void On$eventName$($eventName$EventArgs e) { var handler = $eventName$; if (handler != null) handler(this, e); }]]> System

    And here's one that has two properties:

    
    
      
        
    Generic event with two types/arguments. ev2Generic Code snippet for event handler and On method Ryan Lundy Expansion
    type1 Type of the first property in the EventArgs subclass. propertyType1 arg1Name Name of the first argument in the EventArgs subclass constructor. property1Name property1Name Name of the first property in the EventArgs subclass. Property1Name type2 Type of the second property in the EventArgs subclass. propertyType1 arg2Name Name of the second argument in the EventArgs subclass constructor. property1Name property2Name Name of the second property in the EventArgs subclass. Property2Name eventName Name of the event NameOfEvent $eventName$; protected virtual void On$eventName$($eventName$EventArgs e) { var handler = $eventName$; if (handler != null) handler(this, e); }]]> System

    You can follow the pattern to create them with as many properties as you like.

提交回复
热议问题