问题
Hey I just came across the following statement
return name != null ? name : "NA";
I am just wondering what this is called in .NET
does the ? stand for i.e. then do this... ?
回答1:
It's a "conditional operator" commonly known as the Ternary operator
It's found in many programming languages.
回答2:
Just to add to everyone else's answers, note that in...
condition ? trueResult : falseResult
...only condition
and either trueResult
or falseResult
(but not both) will be evaluated. That makes it possible to write code like this...
string name = user == null ? "<nobody>" : user.Name;
...without the risk of a NullReferenceException
being thrown since user.Name
will only be evaluated if user
is non-null
. Compare this behavior with VB.NET's If operator and IIf function.
回答3:
As Lion said in the comments, they are called ternary operators
, though they are also known as inline if statmenets
and conditional operator
.
If you want to find out more about them, this Wikipedia page will help, and it has examples for many programming languages: http://en.wikipedia.org/wiki/%3F:
回答4:
This is the conditional operator which is a ternary operator. Since there are not so many other ternary operators (operator with three arguments) many people believe its called ternary operator, which is imprecise!
来源:https://stackoverflow.com/questions/9695493/c-sharp-using-if-else-statements-to-set-value-whats-this-called