简体   繁体   English

如何声明一个新的运算符“!??”(测试对象不为null)

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

相关问题 我如何声明:new float [,] [,] {???} - How I can declare that: new float[,][,] {???} 如何声明 GlyphRun object? - How can I declare GlyphRun object? 在第一个关闭后,如何声明第二个新的Application对象? - How can I declare a second, new Application object after the first has shut down? 我可以在对象的 New() 构造函数中声明一个委托吗? 还是带初始化参数? - Can I declare a delegate in an Object's New() constructor? Or with initialization parameters? 如何将Nullable运算符与Null条件运算符一起使用? - How can I use the Nullable Operator with the Null Conditional operator? overload ==(和!=,当然)运算符,我可以绕过==来确定对象是否为空 - overload == (and != , of course) operator, can I bypass == to determine whether the object is null 如何使用条件空运算符检查空字符串? - How can I use the conditional null operator to check for null string? 如何测试十进制为空? - How can I test a decimal for null? 如何测试 LINQ 范围运算符是否已延迟? - How can I test that LINQ Range operator is deferred? 我可以直接在“ if”表达式中声明一个对象吗? - Can I declare an object directly in the “if” expression?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM