关于Nullable的详细介绍可以参考 C#2.0 的新特新和很多的blog文章,这不是我主要想说的内容。只是2.0为了让Nullable类型和non-Nullable数据之间转换,提供了一个新的操作符"??"比较有意思。这个操作符的作用很简单,用法如下:
int? a = 1
;
int? b = null
;
int c = a; // compile error :(
int c = a ?? 100; // right
int d = a + b; // compile error yet
int d = a + b ?? -1; // right
看到这个"??"的使用,你第一时间能想到什么呢?我第一时间就想到了三元操作运算 ? :!
在代码中书写一定的三元运算表达式,很多时候能给我们的代码带来简洁性和紧凑感。不过任何东西都会美中不足,这个经典的三元操作必须有两个分支(嗯,如果一个分支就不是三元了
1.
string param = Request.Params["param"
];
if ( param == null
)

{
param = defaultValue;
}
string param = Request.Params["param"] == null ? defaultValue : Request.Params["param"];
2.
public string
GetValue

{
get
{
if ( this.value == null )
{
return string.Empty;
}
else
{
return this.value;
}
}
}
public string
GetValue

{
get
{
return this.value == null ? string.Empty : this.value;
}
}
在C#2.0中,借助"??"运算符,这类代码将变得非常sexy
1. string params = Reqeust.Params["param"] ?? defaultValue;
2. public string GetValue { get { return this.value ?? string.Empty; } }
3. bool isInternal = this.Session["IsInternal"] as bool? ?? false;
本文介绍了C#2.0实现的Nullable数据类型,它延续了C#人性化特点,避免用object存放简单数据。还着重讲解了新操作符“??”,其用于Nullable类型和non - Nullable数据转换,相比三元操作符,能让代码更简洁,避免重复代码和拼写错误。
280

被折叠的 条评论
为什么被折叠?



