对属性或调用方法使用空合并
可以使用 ??
在这样的情况下操作:
string str = collection["NoRepeate"] ?? null; // Will not compile
//because collection["NoRepeate"] is object
这里的问题是不可能将collection["NoRepeate"]
(即object
)分配给str
并且 collection["NoRepeate"].ToString()
当其值为 null 时抛出异常。
我现在使用条件运算符 ?:
:
str = collection["NoRepeate"].HasValue ? collection["NoRepeate"].ToString() : null
但问题在于重复常量字符串。
It is possible to use the ??
operation in a situation such this:
string str = collection["NoRepeate"] ?? null; // Will not compile
//because collection["NoRepeate"] is object
The problem here is that it is not possible to assign collection["NoRepeate"]
which is object
to str
and collection["NoRepeate"].ToString()
throws exception when its value is null.
I'm using now conditional operator ?:
:
str = collection["NoRepeate"].HasValue ? collection["NoRepeate"].ToString() : null
But the problem is in repeating the constant string.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我同意你的观点,这有点令人烦恼,这不能通过单一声明来完成。空合并运算符在这里没有帮助。
据我所知,最短的需要两个陈述。
I agree with you that it is a bit vexing that this cannot be done in a single statement. The null coalescing operator does not help here.
The shortest I am aware of requires two statements.
您可以执行以下操作:
但这假设该对象实际上是一个字符串。如果不是,您将收到运行时错误。其他解决方案更加强大。
不过,让这个时间尽可能短并没有什么实际意义。你应该让你的代码可读,而不是“我能写多短?”
You can do the following:
This assumes the object is actually a string though. If it's not, you're going to get a run time error. The other solutions are more robust.
There is no real point in getting this to be as short as possible though. You should make your code readable, not "How short can I write this?"
我的解决方案是:
当然,如果你没有原始痴迷,你可以添加一个集合类的方法来执行此操作。否则你可能不得不坚持使用扩展方法。
My solution is:
Of course, if you don't have primitive obsessions you can add a method to the collection class to do this this. Else you'll probably have to stick with an extension method.
从集合返回的对象实际上是
Nullable
Is the object returned from the collection actually a
Nullable<object>
? Otherwise, you probably want to explicitly check for null:是的,如果返回值为 null,则很有可能。如果返回值为“”则否。我一直使用它为空值分配默认值。
Yes that's very possible, if the returned value is null. If the returned value is "" then no. I use it all the time for null values to assign a default.