[英]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.