[英]How can I declare a new operator “!??” (test object is not null)
有没有办法声明一个一元运算符,如'!??'
我想象这样的事情(非工作代码)
public bool operator !??<T> (this <T> item) {
return item != null;
}
所以我会像这样使用它
// day is a value and might possibly be null
string greeting = name !?? "hello there " + name;
我发现自己经常不得不做这种尴尬
// day is a value and might be null
string greeting = day != null ? "hello there " + name : "";
在我提供的示例中相当清楚,但是当您使用getter / setter进行视图模型时,它会让人感到有些困惑,并且会增加错过逻辑错误的可能性。 因此:
public DateTime? SearchDate {
get { return _searchDate; }
set { _searchDate = value != null ? value.Value : value; }
}
这完全不可能。
相反,你可以使用C#6 ?.
运营商:
value?.Value
C#不允许您定义全新的运算符,您只能重载一组特定的现有运算符 。
根本无法在C#中声明新运算符,您只能覆盖现有运算符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.