【发布时间】:2016-06-15 12:17:44
【问题描述】:
有很多问题都有这个错误,但那是因为它似乎是 lambdas 在许多情况下发生的常见错误;但是,我无法确定问题的原因。
我正在使用 Lazy 并且效果很好:
/// <summary>
/// Build a client from the provided data entity.
/// </summary>
/// <param name="fromDataEntity">The data entity from which the client will be built.</param>
/// <returns>The data entity that is built.</returns>
private static Client BuildClient(ClientDataEntity fromDataEntity)
{
var client = new Client()
{
ClientCode = fromDataEntity.ClientCode,
Name = fromDataEntity.Name,
BillingAttorneyLazy = new Lazy<Employee>(() => EmployeeLoading.LoadEmployee(fromDataEntity.BillingAttorneyEmployeeUno))
};
return client;
}
这里EmployeeLoading.LoadEmployee仅供参考:
/// <summary>
/// Load the employee, if it exists, with the provided employee uno.
/// </summary>
/// <param name="withEmployeeUno">The employee uno for the employee that will be loaded.</param>
/// <returns>The employee that is loaded, if one exists for the provided uno, or else null.</returns>
internal static Employee LoadEmployee(uint withEmployeeUno)
{
var entity = CmsDataAbstraction.GetEmployeeDataEntity(withEmployeeUno);
return (entity != null) ? BuildEmployee(entity) : null;
}
现在,当我做类似的事情时:
/// <summary>
/// Build and return an employee from the provided data entity.
/// </summary>
/// <param name="fromDataEntity">The data entity from which the employee will be built.</param>
/// <returns>Build and return an employee from the provided data entity.</returns>
private static Employee BuildEmployee(EmployeeDataEntity fromDataEntity)
{
var employee = new Employee()
{
EmployeeCode = fromDataEntity.Code,
WorksiteUserNameLazy = new Lazy<string>(() => GetEmployeeWorksiteUserName(employee))
};
return employee;
}
我在 lambda () => GetEmployeeWorksiteUserName(employee) 上遇到错误:
无法将 lambda 表达式转换为类型“bool”,因为它不是 委托类型
这里是GetEmployeeWorksiteUserName供参考:
/// <summary>
/// Retrieve the Worksite username for the provided employee.
/// </summary>
/// <param name="forEmployee">The employee whose Worksite username will be retrieved.</param>
/// <returns>The Worksite username for the associated employee.</returns>
private static string GetEmployeeWorksiteUserName(Employee forEmployee)
{
var authorADAccountName = FirmInformationDataAbstraction.GetEmployeeActiveDirectoryUsername(forEmployee.EmployeeCode);
if (WorksiteDataAbstraction.UserExists(authorADAccountName))
{
return authorADAccountName;
}
else // user doesn't exist in Worksite.
{
return string.Empty;
}
}
我相信编译器认为我正在尝试调用 Lazy<T> 的构造函数,它需要一个 bool,但有据可查的是,我的方法应该可以工作(例如,参见 this 之类的网站)。
为什么这种方法在第一种情况下运行良好,而在第二种情况下出现错误?我该如何解决?
【问题讨论】:
-
WorksiteUserNameLazy的类型是什么? -
我想你可以尝试强制解决这个问题并使用带有委托和布尔的构造函数
new Lazy<string>(() => GetEmployeeWorksiteUserName(employee), true) -
@juharr -- 谢谢,这涵盖了“如何修复它”部分。我仍然很好奇它为什么会发生。
-
所以我只是尝试重新创建它,但在使用我在 lambda 中创建的变量时出现错误“在声明之前不能使用局部变量”。
-
奇数。我正在重构和消除其他编译器错误。我发现 VS(至少 2013 年)并不总是能提供错误总数,即您必须修复一个才能显示其他错误。也许这就是这里发生的事情。
标签: c# .net visual-studio-2013 lambda lazy-evaluation