C#委托问题 - 这段代码的作用是什么?

时间:2009-09-16 09:38:02

标签: c# c#-3.0 delegates

有人可以向我解释下面的C#代码行是什么吗?

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

真正让我感到难过的是最后的delegate { }件。对于更多上下文,来自PRISM 2附带的ViewInjection示例中的EmployeesListView.xaml.cs的示例。完整的类定义如下所示:

/// <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 个答案:

答案 0 :(得分:16)

这一位:

delegate {}

只需创建相应类型的“no-op”委托。然后将该委托分配给事件的后备变量。这是一种简单的方法,可以避免在引发事件时进行空检查 - 您始终至少有一个处理程序,即无操作处理程序。

这意味着此代码可以很简单:

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

而不是:

EventHandler<DataEventArgs<BusinessEntities.Employee>> handler =EmployeeSelected;
if (handler != null)
{
    handler(this, new DataEventArgs<BusinessEntities.Employee>(selected));
}

答案 1 :(得分:0)

它将它设置为匿名方法,基本上什么都不做。为什么我不确定,也许是为了避免检查或其他什么,但我认为这很邋。。