我正在关注一本书,其中使用 delegate 关键字(根据我的理解)作为要封装在委托中的函数的名称(使用委托对象名称/构造函数调用的函数)。下面是代码:
//Declaration of delegate object AppendChildData
public delegate void AppendChildData(T entityAggregate, object childEntityKeyValue);
//Dictionary of Delegate Objects
private Dictionary<string, AppendChildData> childCallbacks;
//Creation of dictionary object inside constructor of containing class. Also calling the BuildChildCallbacks() function
protected SqlRepositoryBase(IUnitOfWork unitOfWork)
: base(unitOfWork)
{
this.childCallbacks = new Dictionary<string, AppendChildData>();
this.BuildChildCallbacks();
//Other Initializations
}
protected override void BuildChildCallbacks()
{
this.childCallbacks.Add("allowances", delegate(Project project, object childKeyName)
{
this.AppendProjectAllowances(project);
});
}
现在如果仔细观察的话:
delegate(Project project, object childKeyName)
{
this.AppendProjectAllowances(project);
});
已在 BuildChildCallbacks() 函数中声明为字典 childCallBacks 的值。字典 childCallBacks 的这个值是一个名为 delegate() 的函数。为什么?在这种情况下,.NET 如何使用 delegate 关键字?
我关注的书也使用函数名称而不是使用 delegate 关键字,BuildChlidCallBack 的完整代码如下:
protected override void BuildChildCallbacks()
{
this.ChildCallbacks.Add(ProjectFactory.FieldNames.OwnerCompanyId,
this.AppendOwner);
this.ChildCallbacks.Add(
ProjectFactory.FieldNames.ConstructionAdministratorEmployeeId,
this.AppendConstructionAdministrator);
this.ChildCallbacks.Add(ProjectFactory.FieldNames.PrincipalEmployeeId,
this.AppendPrincipal);
this.ChildCallbacks.Add("allowances",
delegate(Project project, object childKeyName)
{
this.AppendProjectAllowances(project);
});
this.ChildCallbacks.Add("contracts",
delegate(Project project, object childKeyName)
{
this.AppendContracts(project);
});
this.ChildCallbacks.Add("contacts",
delegate(Project project, object childKeyName)
{
this.AppendContacts(project);
});
}
经过仔细观察,我发现在字典键不是外键(不是 DataTable 的列)的情况下使用了 delegate 关键字,并且调用这些委托将 NULL 传递给第二个参数,即 delegate() 函数的“childKeyName”。使用字典调用 delegate() 函数的代码如下:
protected virtual T BuildEntityFromReader(IDataReader reader)
{
T entity = this.entityFactory.BuildEntity(reader);
if (this.childCallbacks != null && this.childCallbacks.Count > 0)
{
object childKeyValue = null;
DataTable columnData = reader.GetSchemaTable();
foreach (string childKeyName in this.childCallbacks.Keys)
{
if (DataHelper.ReaderContainsColumnName(columnData, childKeyName))
{
childKeyValue = reader[childKeyName];
}
else
{
childKeyValue = null;
}
this.childCallbacks[childKeyName](entity, childKeyValue);
}
}
return entity;
}
其中函数中的读取器是 IDataReader,它包含 DataTable 中的单个记录/实体/行(函数中的读取器类型是 reader.read)。
我的问题是,为什么委托词被用作函数名称来分配给 childCallBack 字典中的 AppendChildData 委托对象,而不是函数名称? (因为它编译并运行良好)
并且,在这种情况下,.NET 如何使用 delegate 关键字?