【问题标题】:return statement that checks the first two characters before proceeding在继续之前检查前两个字符的 return 语句
【发布时间】:2018-09-18 18:05:36
【问题描述】:
return ship.DefenseType?.PropulsionMethod != null
    ? new BattleMethod(ship.DefenseType.PropulsionMethod)
    : null;

嗨,我上面的当前 return 语句正在返回一个 Propulsion 方法,如果它不为空的话。但是,我的数据库有不同类型的 由字段中的前 2 个字母表示的推进方式(PK、PA、PT 等)。

在进一步进入 return 语句之前,如何检查以确保 PropulsionMethod 以“PK”开头?

在伪代码中,它可能看起来像这样:

if (ship.DefenseType?.PropulsionMethod).startsWith("PK") 
        && ship.DefenseType?.PropulsionMethod != null)
{
    return new BattleMethod(ship.DefenseType.PropulsionMethod)
}
else
{
    return null;
}

我试过了

return ship.DefenseType?.PropulsionMethod != null &&
    ship.DefenseType?.PropulsionMethod.StartsWith("PK")
    ? new BattleMethod(ship.DefenseType.PropulsionMethod)
    : null;

但我收到此错误:

运算符 && 不能应用于 bool 和 bool 类型的操作数?

【问题讨论】:

  • 制作工厂类
  • 您的解决方案有什么问题?在什么情况下它不起作用?

标签: c# asp.net


【解决方案1】:

只需添加这个条件:

    return ship.DefenseType?.PropulsionMethod != null 
    && ship.DefenseType?.PropulsionMethod.StartsWith("PK")
 ? new BattleMethod(ship.DefenseType.PropulsionMethod) : null;

由于运算符是&&,因此如果第一个条件为真(在这种情况下不为空),则将评估第二个条件。

【讨论】:

  • 也许ship.DefenseType?.PropulsionMethod?.StartsWith(...) 就够了吗?
  • @AleksAndreev 谢谢,不会是null,返回null,否则BattleMethod的类不是PropulsionMethod的值。在这种情况下,我们仍然需要一个 if 来检查该值是否为空,或者我们可以返回一个 BattleMethod
  • 我收到此错误:运算符 && 不能应用于 bool 和 bool 类型的操作数?
  • 这是一个愚蠢的错误,因为 && 仅适用于布尔类型,如果它们不是布尔类型,您应该会收到错误。但是请尝试将您的条件放在括号中(...&&...)
【解决方案2】:

您可以直接将 nullable bool 与 true 进行比较:

return ship.DefenseType?.PropulsionMethod?.StartsWith("PK") == true
    ? new BattleMethod(ship.DefenseType.PropulsionMethod)
    : null;

【讨论】:

    猜你喜欢
    • 2013-05-05
    • 1970-01-01
    • 2022-10-08
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    • 2013-11-28
    • 2023-03-13
    • 2016-04-16
    相关资源
    最近更新 更多