C# Delegate problem - what the heck does this code

2019-07-13 22:21发布

Can anyone explain to me what the following line of C# code does?

public event EventHandler<DataEventArgs<BusinessEntities.Employee>> EmployeeSelected = delegate { };

The bit that's really got me stumped is the delegate { } piece at the end. For a bit more context, the sample from the EmployeesListView.xaml.cs in the ViewInjection sample that ships with PRISM 2. The full class definition is shown below:

/// <summary>
/// Interaction logic for EmployeesListView.xaml
/// </summary>
public partial class EmployeesListView : UserControl, IEmployeesListView
{
    public EmployeesListView()
    {
        InitializeComponent();
    }

    public ObservableCollection<BusinessEntities.Employee> Model
    {
        get { return this.DataContext as ObservableCollection<BusinessEntities.Employee>; }
        set { this.DataContext = value; }
    }

    public event EventHandler<DataEventArgs<BusinessEntities.Employee>> EmployeeSelected = delegate { };

    private void EmployeesList_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (e.AddedItems.Count > 0)
        {
            BusinessEntities.Employee selected = e.AddedItems[0] as BusinessEntities.Employee;
            if (selected != null)
            {
                EmployeeSelected(this, new DataEventArgs<BusinessEntities.Employee>(selected));
            }
        }
    }
}

2条回答
劫难
2楼-- · 2019-07-13 22:40

It's setting it to an anonymous method that does nothing basically. Why I'm not sure, maybe to avoid a check or something but I would consider that quite sloppy.

查看更多
冷血范
3楼-- · 2019-07-13 22:44

This bit:

delegate {}

just creates a "no-op" delegate of the appropriate type. That delegate is then assigned to the backing variable for the event. It's a simple way to avoid having to do null checks when raising an event - you always have at least one handler, which is the no-op handler.

It means that this code can be simple:

EmployeeSelected(this, new DataEventArgs<BusinessEntities.Employee>(selected));

Instead of:

EventHandler<DataEventArgs<BusinessEntities.Employee>> handler =EmployeeSelected;
if (handler != null)
{
    handler(this, new DataEventArgs<BusinessEntities.Employee>(selected));
}
查看更多
登录 后发表回答