【发布时间】:2022-10-22 03:22:04
【问题描述】:
阅读文档时,在检查可空性时,我对模式匹配和赋值的含义并不是 100% 清楚
考虑:
#nullable enable
record EmployeeData(string Name, int Age);
bool F(string employeeName) {
EmployeeData? employee = repository.Get(employeeName); // return null if not found
if (employee is null) return false;
// do something with employee it is not null
return true;
}
这可以正确地写成:
bool F(string employeeName) {
if (repository.Get(employeeName) is not EmployeeData employee) return false;
// do something with employee it is not null
return true;
}
注意:我想做:
if (repository.Get(employeeName) as EmployeeData employee is null) return false;
这是很多更清晰,但这不能编译:(或者有更好的方法吗?
【问题讨论】:
-
“这能正确地写成……吗?”你试过了吗?如果它有效,那么它可以,对吗?或者您是否正在寻找一些官方文档,上面写着“是的,这是受支持的行为”?
-
从知识渊博的来源寻求确认,这很好。是的,它似乎在 null 时正确返回 false 并且当我没有收到警告说员工在那之后可以为 null 时
标签: c#