Action vs delegate event

2019-01-21 03:46发布

I have seen developers using the below codes quite alternatively. What is the exact difference between these, and which ones go by the standard? Are they same, as Action and Func<T> is a delegate as well:

public event Action<EmployeeEventAgs> OnLeave;
public void Leave()
{
    OnLeave(new EmployeeEventAgs(this.ID));
}

VS

public delegate void GoOnLeave(EmployeeEventAgs e);
public event GoOnLeave OnLeave;
public void Leave()
{
    OnLeave(new EmployeeEventAgs(this.ID));
}

标签: c# delegates
8条回答
唯我独甜
2楼-- · 2019-01-21 04:17

Fwiw, neither example uses standard .NET conventions. The EventHandler<T> generic should declare the event:

public event EventHandler<EmployeeEventArgs> Leave;

The "On" prefix should be reserved for a protected method that raises the event:

protected virtual void OnLeave(EmployeeEventArgs e) {
    var handler = Leave;
    if (handler != null) handler(this, e);
}

You don't have to do it this way, but anybody will instantly recognize the pattern, understand your code and know how to use and customize it.

And it has the great advantage of not being forced to choose between a custom delegate declaration and Action<>, EventHandler<> is the best way. Which answers your question.

查看更多
甜甜的少女心
3楼-- · 2019-01-21 04:30

Action<T> is exactly the same as delegate void ... (T t)

Func<T> is exactly the same as delegate T ... ()

查看更多
太酷不给撩
4楼-- · 2019-01-21 04:32

Action is just a shortcut for the full delegate declaration.

public delegate void Action<T>(T obj)

http://msdn.microsoft.com/en-us/library/018hxwa8.aspx

Which one to use would depend on your organizations coding standards/style.

查看更多
Luminary・发光体
5楼-- · 2019-01-21 04:33

In general, they are equivalent. But in the context of using a delegate for the type of an event, the convention is to use EventHandler (where T inherits EventArgs):

public event EventHandler<EmployeeEventArgs> Left;

public void Leave()
{
    OnLeft(this.ID);
}

protected virtual void OnLeft(int id)
{
    if (Left != null) {
        Left(new EmployeeEventArgs(id));
    }
}
查看更多
Ridiculous、
6楼-- · 2019-01-21 04:37

You could have written these Action and Func generic delegates yourself, but since they're generally useful they wrote them for you and stuck them in .Net libraries.

查看更多
干净又极端
7楼-- · 2019-01-21 04:39

Yes, Action and Func are simply convenience delegates that have been defined in the 3.5 clr.

Action, Func and lambdas are all just syntactical sugar and convenience for using delegates.

There is nothing magic about them. Several people have written simple 2.0 addon libraries to add this functionality to 2.0 code.

查看更多
登录 后发表回答