[英]How can I declare a new operator “!??” (test object is not null)
Is there a way to declare a unary operator such as '!??' 有没有办法声明一个一元运算符,如'!??'
I imagine something like this (non working code) 我想象这样的事情(非工作代码)
public bool operator !??<T> (this <T> item) {
return item != null;
}
so I would use it like such 所以我会像这样使用它
// day is a value and might possibly be null
string greeting = name !?? "hello there " + name;
I find myself often having to do this awkwardness 我发现自己经常不得不做这种尴尬
// day is a value and might be null
string greeting = day != null ? "hello there " + name : "";
It's fairly clear in the example I've provided, but when you are using getter/setters for view-models, it gets a bit confusing to stare at, and raises the chance of a logical error being missed. 在我提供的示例中相当清楚,但是当您使用getter / setter进行视图模型时,它会让人感到有些困惑,并且会增加错过逻辑错误的可能性。 As such:
因此:
public DateTime? SearchDate {
get { return _searchDate; }
set { _searchDate = value != null ? value.Value : value; }
}
This is completely impossible. 这完全不可能。
Instead, you can use C# 6's ?.
相反,你可以使用C#6
?.
operator: 运营商:
value?.Value
As has been said, you cannot declare new operators in C#, ever, at all. 如前所述,您根本无法在C#中声明新的运算符。 This is a limitation of the language, the compiler, and the environment.
这是语言,编译器和环境的限制。
What you CAN do is utilize the null coalescing operator or write a few generic Extension Methods to handle what you want, such as 您可以做的是利用空合并运算符或编写一些通用的扩展方法来处理您想要的内容,例如
public static string EmptyIfNull(this string source, string ifValue, string ifNull = "")
{
return source != null ? ifValue : ifNull;
}
and implemented via 并通过实施
string greeting = name.EmptyIfNull("hello there " + name);
C#不允许您定义全新的运算符,您只能重载一组特定的现有运算符 。
根本无法在C#中声明新运算符,您只能覆盖现有运算符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.