美文网首页
Operator : Nullable Types

Operator : Nullable Types

作者: 津涵 | 来源:发表于2019-02-13 10:16 被阅读0次

Nullable Types and Operators

(1)陈述:
An important difference between value types and reference types is that reference types can be null. A value type, such as int, cannot be null. This is a special issue on mapping C# types to database types. A database number can be null. In earlier C# versions, a solution was to use a reference type for mapping a nullable database number. However, this method affects performance because the garbage collector needs to deal with reference types. Now you can use a nullable int instead of a normal int. The overhead for this is just an additional Boolean that is used to check or set the null value. A nullable type still is a value type.
(2)可空类型:
int? a=1;
long? b = null;
DateTime? d = null;
(3)运算:有空则为空
Usually, when using a unary or binary operator with nullable types, the result will be null if one or both of the operands is null.
coding:
int? a = null;
int? b = a + 4; // b = null
int? c = a * 5; // c = null
(4)比较:有空则为false
When comparing nullable types, if only one of the operands is null, the comparison always equates to false.
coding:
int? a = null;
int? b = -5;
if (a >= b) // if a or b is null, this condition is false

The Null Coalescing Operator

(1)null values
规则:
If the first operand is not null, then the overall expression has the value of the first operand.
If the first operand is null, then the overall expression has the value of the second operand.
coding:
int? a = null;
int b;
b = a ?? 10; // b has the value 10
a = 3;
b = a ?? 10; // b has the value 3
注:If the second operand cannot be implicitly converted to the type of the first operand, a compile-time error is generated.
(2)null references
coding:
private MyClass _val;
public MyClass Val
{
get => _val ?? (_val = new MyClass());
}

The Null-Conditional Operator

减少代码,判空
(1)当p为null,只返回null,不再取其属性
Using the null-conditional operator to access the FirstName property (p?.FirstName), when p is null, only null is returned without continuing to the right side of the expression.
coding:
public void ShowPerson(Person p)
{
string firstName = p?.FirstName;
//...
}
(2)使用

int? age = p?.Age;

int ageTwo = p?.Age??0;

Person p = GetPerson();
string city = null;

if (p != null && p.HomeAddress != null)
{
city = p.HomeAddress.City;
}
等价简写:
string city = p?.HomeAddress?.City;
4)array中也可使用
int x = arr?[0]??0;

Others其它知识点小结

right-associative
(1)赋值“=”
coding:
int z = 3;
int y = 2;
int x = 1;
x = y = z;
结果:Because of the right associativity, all variables x, y, and z have the value 3 because it is evaluated from right to left.
(2)三目运算符
a ? b: c ? d: e
等价于
a = b: (c ? d: e)

相关文章

网友评论

      本文标题:Operator : Nullable Types

      本文链接:https://www.haomeiwen.com/subject/ptereqtx.html