【问题标题】:How to use shortcut operators (?. ??) in this case? [duplicate]在这种情况下如何使用快捷操作符 (?. ??)? [复制]
【发布时间】:2019-09-09 18:36:01
【问题描述】:

这是我的代码的简化版本。

class Address
{
    public bool IsAppartment { get; set; }
}

class Employee
{
    public string Name { get; set; }
    public Address Address { get; set; }
} 

class Program
{
    static void Main(string[] args)
    {
       Employee employee = new Employee()
       {
           Name = "Charlie"
       };
       if (employee.Address == null || !employee.Address.IsAppartment)
       {
           Console.WriteLine("Hello in if");
       }
       else
       {
           Console.WriteLine("Hello in else");
       }
   }
}

有没有办法使用任何短运算符(例如?)来重写以下代码行。要么 ??或任何其他的?

if (employee.Address == null || !employee.Address.IsAppartment)

【问题讨论】:

  • 我不认为它是重复的。该问题的解决方案会导致编译错误。
  • 这已在您最近的其他问题的答案和 cmets 中得到充分解决。
  • if (!employee.Address?.IsApartment ?? true) ?? 之前的部分首先被评估。如果它有一个null 值,则评估并返回右侧(并且您希望为空返回true,所以我们只使用true)。如果它没有null 值,则返回左值。员工前面的感叹号是"logical negation" operator - 如果IsApartmentfalse,感叹号会将其翻转为true

标签: c# .net .net-4.6.1


【解决方案1】:

是的。 ?. 运算符的全部意义在于避免在这种情况下检查 null。简单写:

if (employee.Address?.IsAppartment)

【讨论】:

  • 无法将bool? 转换为bool
  • employee.Address == null 时,这不会返回true
  • 那我不明白这个问题?如果他想在 Address 为 null 时返回 true,或者在 IsApartment 属性为 true 时返回 true,那是两种完全不同的情况,无法避免出现两种情况。
  • 如果你想trueemployee.Address == null,你必须在你写的表达式的末尾添加?? true。否则,添加?? false。无论哪种方式,您都需要对employee.Address == null 时得到的null 执行某些操作,否则会出现编译器错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-13
  • 1970-01-01
  • 2013-07-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多