简体   繁体   中英

C# Delegate problem - what the heck does this code do?

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));
            }
        }
    }
}

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));
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM