The question mark (? (Usage summary
- 2020-06-19 11:39:51
- OfStack
1. Nullable type modifier (?) :
A reference type can use a null reference to represent a value that does not exist, and a value type usually cannot be represented as null.
Such as:
string str = null; That's right.
int i = null; Compiler will report an error.
In order for a value type to be nullable as well, a nullable type appears, using the nullable type modifier? Is expressed as T? .
Example: int & # 63; Indicates that the plastic is void,DateTime? Represents the time that is available.
T & # 63; In fact is System Nullable
<
T
>
Short for generic structure, which means when you use T? The time compiler puts T? Compiled into System Nullable
<
T
>
In the form of,
For example: int & # 63; , System.Nullable
<
int
>
In the form.
2. 3 yuan (operator) expression (? :) :
The syntax is: conditional expression? Expression 1: Expression 2;
This operation first evaluates the value of the conditional expression (type bool), calling expression 1 for true and expression 2 for flase.
The logic is: "If execute the first for true, otherwise execute the second."
Ex. :
test ? expression1 : expression2
test Any Boolean expression.
expression1 test is the expression returned when true. It could be a comma expression.
expression2 test is the expression returned when false. It could be a comma expression.
Such as:
string prm1="4"; string prm2="5";
string prm3 prm1 of = = = prm2 & # 63;" yes":"no" // The value of prm3 is "no".
3. Null merge operator (??) :
Null merge operator (null coalescing operator) ? The & # 63;
Used to define default values for nullable and reference types. If the left operand of this operator is not null, then this operator returns the left operand; Otherwise returns the right operand.
Example: a & # 63; The & # 63; If a is not empty, then a ? The & # 63; The result of b is a; Otherwise the result is b.
The null merge operator is the right join operator, that is, the operator is combined from right to left.
Example: "a & # 63; The & # 63; b & # 63; The & # 63; For c, click 'a? The & # 63; (b & # 63; The & # 63; c) ".