C# Action/Delegate Style Question

我们两清 提交于 2019-12-04 02:52:36

Neither 1 or 2. A third option is the winner

public event EventHandler<NumberChangedEventArgs> NumberChanged;

You're breaking a number of style guidelines for developing in C#, such as using a type for event args that doesn't extend EventArgs.

Yes, you can do it this way, as the compiler doesn't care. However, people reading your code will do a WTF.

Don't create a new type if you don't have to. I think this is better:

public event Action<object, double> OnNumberChanged;

The reason that the Action and Func delegate families exist is to serve this very purpose and reduce the need for new delegate type creation by developers.

Typically I stick to using an EventArgs derived class as the argument. It makes the code much more consistent.

I have a class:

public class ApplyClickedEventArgs : EventArgs  
{  
   ...
}

and a handler:

void cpy_ApplyClicked(object sender, ApplyClickedEventArgs e)  
{  
   ...  
}  

The declaration is:

public event EventHandler<ApplyClickedEventArgs> ApplyClicked;

As with all questions about coding style. Pick the one you prefer, or that your team prefers, and keep it consistent throughout the project. As long as everyone who needs to can read it efficiently you will be fine.

I think option 1 is better if I were to choose, but IIRC, the official guidelines for events state that your second parameter has to be a class with the name XxxEventArgs, and should have EventArgs up in its inheritance chain.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!