gpt4 book ai didi

C# 委托(delegate)问题 - 这段代码到底做了什么?

转载 作者:行者123 更新时间:2023-11-30 18:55:55 25 4
gpt4 key购买 nike

任何人都可以向我解释以下 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));
}
}
}
}

最佳答案

这个位:

delegate {}

只是创建一个适当类型的“无操作”委托(delegate)。然后将该委托(delegate)分配给事件的支持变量。这是一种避免在引发事件时必须进行空值检查的简单方法 - 您始终至少有一个处理程序,即无操作处理程序。

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

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

代替:

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

关于C# 委托(delegate)问题 - 这段代码到底做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1431982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com