c# - 为什么这个三元语句在简写时会返回误报?
问题描述
我一直在摸索这个问题,因为除了格式之外,这些语句似乎几乎相同 - 但是速记语句的评估方式似乎不同,并且在不应该返回 true 时会产生误报。
在下面的例子中,想象programRecord.Award = 'Emmy'
和targetAward = 'Oscar'
错误代码给出误报:
private bool MatchMe(string programId, string targetAward, string targetLevel, Program programRecord)
{
var isMatched = programRecord.Status == "Active"
&& string.IsNullOrEmpty(programId) ? true : programRecord.Pid == programId
&& string.IsNullOrEmpty(targetAward) ? true : programRecord.Award == targetAward
&& string.IsNullOrEmpty(targetLevel) ? true : programRecord.Level == targetLevel;
return isMatched;
}
好代码:
private bool MatchMe(string programId, string targetAward, string targetLevel, Program programRecord)
{
var isMatched = programRecord.Status == "Active";
var isMatched2 = string.IsNullOrEmpty(programId) ? true : programRecord.Pid == programId;
var isMatched3 = string.IsNullOrEmpty(targetAward) ? true : programRecord.Award == targetAward;
var isMatched4 = string.IsNullOrEmpty(targetLevel) ? true : programRecord.Level == targetLevel;
var doIMatch = isMatched && isMatched2 && isMatched3 && isMatched4;
return doIMatch;
}
导致这种情况的速记版本中发生了什么?我认为一个 false 值会强制整个语句返回 false,但是缩写版本不会发生这种情况。
解决方案
您比较的格式是错误的。如果要正确解释,您实际上需要括号来强制内联。
你应该有以下内容
private bool MatchMe(string programId, string targetAward, string targetLevel, Program programRecord)
{
var isMatched = programRecord.Status == "Active"
&& (string.IsNullOrEmpty(programId) ? true : programRecord.Pid == programId)
&& (string.IsNullOrEmpty(targetAward) ? true : programRecord.Award == targetAward)
&& (string.IsNullOrEmpty(targetLevel) ? true : programRecord.Level == targetLevel);
return isMatched;
}
推荐阅读
- kubernetes - 更改 Kubernetes 集群 ip 范围
- javascript - PapaParse 脚本路径未定义
- selenium - Selenium Webdriver 从哪个地方获得标题 - 使用 driver.title
- python - Python 如何刷新 Psutil 结果?
- php - Prestashop购物车和订单生命周期,如何“确认”购物车并使其成为来自外部支付方式的订单
- android - AppCompatEditText 未正确显示项目符号
- c# - 检查 CheckListBox 中的选定项目
- node.js - 请求:无法通过管道将响应发送到文件系统
- javascript - 使用 async/await 是从 Promise.reject() 接收已解决承诺的唯一方法吗?
- multithreading - 多线程实际上是否在单处理器环境中工作