【发布时间】: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 - 如果IsApartment是false,感叹号会将其翻转为true。
标签: c# .net .net-4.6.1