合并运算符 - 用法 (c#)
我看到越来越多的代码片段以一种(无论如何对我来说)有点奇怪的方式使用合并运算符,对此用法有何想法?
例如做:
string foo = null;
void bar(){
foo = foo??"hello";
}
而不是
string foo = null;
void bar(){
if (foo==null)
foo="hello";
}
Ive seen an increasing number of pieces of code that use the coalesce operator in a (to me anyway) slightly odd manner, thoughts on this usage?
e.g. doing:
string foo = null;
void bar(){
foo = foo??"hello";
}
instead of
string foo = null;
void bar(){
if (foo==null)
foo="hello";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对我来说,这看起来是空合并运算符的完全合理的使用。请注意,它与第一个代码片段完全不同,因为无论哪种方式它都会重新分配
foo
。如果您实际上使用属性而不是变量,这可能很重要 - 无论当前值如何,都会调用属性设置器。That looks like an entirely reasonable use of the null coalescing operator to me. Note that it's not quite the same as the first code snippet, as it will be reassigning
foo
either way. This could be significant if you were actually using a property rather than a variable - the property setter would be invoked regardless of the current value.它使代码更短、更具可读性,同时提供检查空对象的虚拟功能。
It makes code shorter and more readable while providing the vitual functionality of checking on null objects.
主要区别因素是
??
是一个运算符,因此可以在其他表达式中使用。至于在哪里使用它——完全取决于开发人员。The main differentiating factor is that
??
is an operator and can therefore be used in other expressions. As to where to use it -- it's completely up to developer.这是一个令人惊奇的情况,合并运算符可能会有所帮助。感谢埃里克。
请点击链接和 Eric 的回答
An Amazing situation where Coalesce Operator may be helpful. Thanks to Eric.
Please follow the link and Eric's Answer