C#2.0实现的Nullable数据类型,虽然说只是一个小小的cookie,但不得不说是C#矢志不渝的延续了它人性化的特点,我们终于不用再使用object来存放简单数据来通过==null测试。从表面上看这个功能或许并无太大的创新意义,但不知你是否也和我一样在记忆里埋有对类似int a=null;通不过编译时的抱怨?
关于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
看到这个"??"的使用,你第一时间能想到什么呢?我第一时间就想到了三元操作运算 ? :!
在代码中书写一定的三元运算表达式,很多时候能给我们的代码带来简洁性和紧凑感。不过任何东西都会美中不足,这个经典的三元操作必须有两个分支(嗯,如果一个分支就不是三元了
),所以我有时不得不为了不使用if语句,而写下一些自感丑陋蹩脚代码:
1.
string param = Request.Params["param"];
if ( param ==
null )


{
param = defaultValue;
}
或
string param = Request.Params["param"] ==
null
? defaultValue : Request.Params["param"];
我是比较反感把类似Request.Params["key"]、ViewState["key"]以及Hasttable["key"]这类的相同代码写超过一遍的,因为作为key的literal string不能被编译器检查,出现拼写错误后是非常让人抓狂的。
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; } }
关于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"];
我是比较反感把类似Request.Params["key"]、ViewState["key"]以及Hasttable["key"]这类的相同代码写超过一遍的,因为作为key的literal string不能被编译器检查,出现拼写错误后是非常让人抓狂的。
2.
publicstring GetValue


{
get
{
if ( this.value ==null )

{
returnstring.Empty;
}
else
{
returnthis.value;
}
}
}或
publicstring GetValue


{
get
{
returnthis.value ==
null
?
string.Empty : this.value;
}
}使用?:后貌似不错了,但似乎还不是我们希望的终极无间...
在C#2.0中,借助"??"运算符,这类代码将变得非常sexy
params
= Reqeust.Params["param"] ?? defaultValue;
2. public
string GetValue
{ get
{ return
this.value ??
string.Empty; } }

添加至收藏夹