C#的??运算符

??可能是一个被遗忘的运算符,很少看到有人用它,它的用法很简单却很实用:
variable ?? defaultValue
相当于
variable == null ? defaultValue : variable
有了它,一行便能搞定Lazy Evaluation了:
使用??之前:

public UserAccess Users
{
    
get
    {
        
if (_users == null)
        {
            _users 
= Proxy.GetQueryObject<UserAccess>();
        }
        
return _users;
    }
}


之后:

public UserAccess Users
{
    
get
    {
        
return _users ?? (_users = Proxy.GetQueryObject<UserAccess>());
    }
}


注:这个运算符只支持引用类型和Nullable类型。

posted @ 2012-07-28 19:42  xust  阅读(132)  评论(0)    收藏  举报