C#2.0终于有了?:便捷判断的单分支版

本文介绍了C#2.0实现的Nullable数据类型,它延续了C#人性化特点,避免用object存放简单数据。还着重讲解了新操作符“??”,其用于Nullable类型和non - Nullable数据转换,相比三元操作符,能让代码更简洁,避免重复代码和拼写错误。
    C#2.0实现的Nullable数据类型,虽然说只是一个小小的cookie,但不得不说是C#矢志不渝的延续了它人性化的特点,我们终于不用再使用object来存放简单数据来通过==null测试。从表面上看这个功能或许并无太大的创新意义,但不知你是否也和我一样在记忆里埋有对类似int a=null;通不过编译时的抱怨?

    关于Nullable的详细介绍可以参考
C#2.0 的新特新和很多的blog文章,这不是我主要想说的内容。只是2.0为了让Nullable类型和non-Nullable数据之间转换,提供了一个新的操作符"??"比较有意思。这个操作符的作用很简单,用法如下:
None.gif int? a = 1 ;
None.gif 
int? b = null
;
None.gif 
int c = a; // compile error :(

None.gif 
int c = a ?? 100// right
None.gif 
int d = a + b; // compile error yet
None.gif 
int d = a + b ?? -1// right

    看到这个"??"的使用,你第一时间能想到什么呢?我第一时间就想到了三元操作运算 ? :

    在代码中书写一定的三元运算表达式,很多时候能给我们的代码带来简洁性和紧凑感。不过任何东西都会美中不足,这个经典的三元操作必须有两个分支(嗯,如果一个分支就不是三元了emembarrassed.gif),所以我有时不得不为了不使用if语句,而写下一些自感丑陋蹩脚代码:
    1.
None.gifstring param = Request.Params["param" ];
None.gif
if ( param == null
 )
ExpandedBlockStart.gifContractedBlock.gif
dot.gif
{
InBlock.gif    param = defaultValue;
ExpandedBlockEnd.gif}
None.gif
    或
None.gifstring param = Request.Params["param"== null ? defaultValue : Request.Params["param"];
    我是比较反感把类似Request.Params["key"] 、ViewState["key"]以及Hasttable["key"]这类的相同代码写超过一遍的,因为作为key的literal string不能被编译器检查,出现拼写错误后是非常让人抓狂的。

    2.
None.gifpublic string  GetValue
ExpandedBlockStart.gifContractedBlock.gif
dot.gif
{
InBlock.gif    
get

ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
if ( this.value == null
 )
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif
{
InBlock.gif            
return string
.Empty;
ExpandedSubBlockEnd.gif        }

InBlock.gif        
else
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return this
.value;
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}
    或
None.gifpublic string  GetValue
ExpandedBlockStart.gifContractedBlock.gif
dot.gif
{
InBlock.gif    
get

ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
return this.value == null ? string.Empty : this
.value;
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}
    使用?:后貌似不错了,但似乎还不是我们希望的终极无间...

    在C#2.0中,借助"??"运算符,这类代码将变得非常sexytongue_smile.gif
 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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值