Pat*_*k Q 2 c# generics nullable unary-operator
有没有办法声明一个一元运算符,如'!??'
我想象这样的事情(非工作代码)
public bool operator !??<T> (this <T> item) {
return item != null;
}
Run Code Online (Sandbox Code Playgroud)
所以我会像这样使用它
// day is a value and might possibly be null
string greeting = name !?? "hello there " + name;
Run Code Online (Sandbox Code Playgroud)
我发现自己经常要做这种尴尬
// day is a value and might be null
string greeting = day != null ? "hello there " + name : "";
Run Code Online (Sandbox Code Playgroud)
在我提供的示例中相当清楚,但是当您使用getter/setter进行视图模型时,它会让人感到有些困惑,并且会增加错过逻辑错误的可能性.因此:
public DateTime? SearchDate {
get { return _searchDate; }
set { _searchDate = value != null ? value.Value : value; }
}
Run Code Online (Sandbox Code Playgroud)