C# Action/Delegate Style Question

丶灬走出姿态 提交于 2019-12-05 21:33:49

问题


What is considered better style for an event definition:

public event Action<object, double> OnNumberChanged;

or

public delegate void DNumberChanged(object sender, double number);
public event DNumberChanged OnNumberChanged;

The first takes less typing, but the delegate one gives names to the parameters. As I type this, I think number 2 is the winner, but I could be wrong.

Edit: A different (third) approach is the winner. Read below.


回答1:


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.




回答2:


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.




回答3:


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;



回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/1120670/c-sharp-action-delegate-style-question

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