问题
Here is my code
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?.IsAppartment ?? true)
{
Console.WriteLine("Its an apartment");
}
else
{
Console.WriteLine("No employee address or not an apartment");
}
}
}
The output of this program
Its an apartment
According to the definition of ?. operator
if one operation in a chain of conditional member or element access operations returns null, the rest of the chain doesn't execute.
In this case, Address object is null, I don't understand why it's not going in the else branch of the code here?
UPDATE
What will be equivalent code for following using short cut operators?
if (employee.Address != null && employee.Address.IsAppartment == true)
{
Console.WriteLine("Its an apartment");
}
else
{
Console.WriteLine("No employee address or not an apartment");
}
回答1:
This is correct, the rest of the chain doesn't execute, null-coalescing operator operator ?? works and returns true
. Per MSDN
The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result.
If you want to compare the result with either true
or false
(per your update) you can use
if (employee?.Address?.IsAppartment == true)
{
}
The left-hand operand returns Nullable<bool>
, you can also read about it in MSND
回答2:
UPDATE What will be equivalent code for following using short cut operators?
if (employee.Address != null && ? employee.Address.IsAppartment == true)
if (employee?.Address?.IsAppartment == true)
回答3:
Please check the MSDN, ?: operator - https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator
??: operator - https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator
hope it will help you.. :-)
回答4:
if (employee.Address?.IsAppartment ?? true)
{
Console.WriteLine("Its an apartment");
}
means
if (employee.Address != null && employee.Address.IsAppartment != null && employee.Address.IsAppartment == true)
{
Console.WriteLine("Its an apartment");
}
This make your code does not throw the NullReferenceException when employee.Address
be null.
Dont need to use ?? true
because in C#, your IsAppartment
property 's data-type is bool
. When you do declaration of an instance of Address
class, value of IsAppartment
will be false
automatically, it canot be null (bool
is difference from bool?
).
So, you only need do this:
if (employee.Address?.IsAppartment)
{
Console.WriteLine("Its an apartment");
}
来源:https://stackoverflow.com/questions/57859267/confused-about-behavior-of-operator