您如何看待 C# 中的 ??= 运算符?
您认为 C# 会支持 ??= 运算符之类的东西吗?
而不是这样:
if (list == null)
list = new List<int>();
可能可以写:
list ??= new List<int>();
现在,我可以使用(但在我看来不太可读):
list = list ?? new List<int>();
Do you think that C# will support something like ??= operator?
Instead of this:
if (list == null)
list = new List<int>();
It might be possible to write:
list ??= new List<int>();
Now, I could use (but it seems to me not well readable):
list = list ?? new List<int>();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
就我个人而言,我认为只有第二个扩展才有意义(就与
+=
等保持一致而言):但说实话,我发现它有点不必要。人们通常会“得到”
i += 5;
,但往往会遇到空合并问题 (??
)。添加一个空合并赋值运算符并且......好吧,我认为它的结局不太好。就我个人而言,我更喜欢原始代码:
另外 - 考虑:在所有其他
+=
、-=
等中 - 总是评估右侧。在这种情况下,它不会(在某些情况下)。这增加了更多的混乱。我的意思是:Personally I think only the second expansion makes sense (in terms of keeping along the same line as
+=
etc):but to be honest I find it a little bit unnecessary. People usually "get"
i += 5;
, but tend to have a problem with null-coalescing (??
). Add a null-coalescing-assignment operator and... well, I don't see it ending well.Personally I favor the original code:
Also - consider: in all the other
+=
,-=
etc - the right hand side is always evaluated. In this case it wouldn't be (in some cases). That adds even more confusion. By which I mean:我一直想要这样的东西。我会比
??
本身更频繁地使用它。不过,我真正想要的是一种运算符形式,它允许您仅在非空时取消引用该对象。替换这个: 用
这样的东西:
这对我来说特别有用,有长引用链(我知道设计不好),但是例如,
这目前不可能用
??
因为你只能说“分配给 foo,或者如果为 null,则为替代项”,而不能说“分配给 foo 的属性,或者如果为 null,则为替代项”。I have always wanted something like this. I would use it far more often than the
??
by itself.What I REALLY want, though, is a form of operator that lets you dereference the object only if non null. To replace this:
with something like this:
Which would be especially useful for me with long chains of references (bad design, I know), but for example
This isn't currently possible with
??
because you can only say "assign to foo, or an alternative if null" but not "assign to a property of foo, or an alternative if null."我在 stackoverflow 上发现的一个技巧是做这样的事情......
你也许可以在代码中使用类似的惰性 eval 。
A trick I found somewhere here on stackoverflow was to do something like this...
... you maybe able to use similar lazy eval in your code.
我喜欢它——这是表达延迟加载表达式的一种很好、简洁的方式。它是否被添加到语言中完全是另一回事 - 如 Eric Lippert 喜欢指出,新功能需要大量工作来实现,因此它们必须为语言做出显着的净积极贡献才能被包含在内。
I like it - it is a nice, succinct way to express a lazy-loading expression. Whether or not it gets added to language is another thing altogether - as Eric Lippert loves to point out, new features require significant amounts of work to implement and as such they must contribute a significant net positive to the language in order to be included.
除非我读错了你的问题,否则该运算符确实存在于 C# 中: http://msdn.microsoft.com/en-us/library/ms173224(VS.80).aspx
Unless I read your question wrong, that operator does exist in C#: http://msdn.microsoft.com/en-us/library/ms173224(VS.80).aspx