将 HasValue 重写为 ??运营商
重写以下代码是否安全:
bool b = foo.bar.HasValue ? foo.bar.Value : false;
其中
bool b = foo.bar.Value ?? false;
bar
是可空类型 bool?
Is it safe to rewrite the following code:
bool b = foo.bar.HasValue ? foo.bar.Value : false;
to
bool b = foo.bar.Value ?? false;
where bar
is the nullable type bool?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
最简单的修复
实际上也比
.Value
更便宜,因为它省略了 has-value 检查。它将默认为default(T)
,这里确实是false
(它只是返回底层T
字段的值,没有任何检查根本没有)。如果您需要与
default(T)
不同的默认值,则:The easiest fix there is
which is also actually cheaper than
.Value
as it omits the has-value check. It will default todefault(T)
, which is indeedfalse
here (it just returns the value of the underlyingT
field, without any checks at all).If you need a different default to
default(T)
, then:您想要的是:
这是(令人惊讶的)安全的,并且是空合并运算符的预期用途。
来源:http://msdn.microsoft.com/en-us/library/ms173224.aspx
对于
Nullable
,它在功能上等同于Nullable.GetValueOrDefault(T defaultValue)
。代码:
将导致编译器错误,因为您无法将运算符应用于值类型,并且
Nullable.Value
始终返回值类型(或者在没有值时抛出异常)。What you want is:
This is (surprisingly) safe and an intended use for the null-coalescing operator.
Source: http://msdn.microsoft.com/en-us/library/ms173224.aspx
In the case of
Nullable<T>
, it is functionally equivalent toNullable<T>.GetValueOrDefault(T defaultValue)
.The code:
Will cause a compiler-error, because you cannot apply the operator to value types, and
Nullable<T>.Value
always returns a value-type (or throws an exception when there is no value).不——这不安全。
则该行:
如果 foo.bar 没有值,
将抛出 InvalidOperationException。相反,使用
Update - 我刚刚从其他答案中了解到
.GetValueOrDefault();
- 这看起来是一个非常好的使用建议!更新 2 - @ProgrammingHero 的答案也是正确的(添加了 +1!) - 该行:
实际上不会编译 - 因为
Error 50 Operator '??'不能应用于“bool”和“bool”类型的操作数
No - this is not safe.
The line:
will throw an InvalidOperationException if foo.bar has no value.
Instead use
Update - I just learned about
.GetValueOrDefault();
from the other answers - that looks like a very good suggestion to use!Update 2 - @ProgrammingHero's answer is also correct (+1 added!) - the line:
actually won't compile - because of
Error 50 Operator '??' cannot be applied to operands of type 'bool' and 'bool'
没有。
来自: http://msdn.microsoft.com /en-us/library/1t3y8s4s%28v=vs.80%29.aspx
因此,如果 hasValue 为 false,那么您将在第二个中抛出异常当你尝试运行它时。
Nope.
From: http://msdn.microsoft.com/en-us/library/1t3y8s4s%28v=vs.80%29.aspx
So if hasValue is false then you will get an exception thrown in your second one when you try to run it.
ffoo.bar ?? false
使用起来会更安全ffoo.bar ?? false
would be more safer to use有编译错误,因为 ?? 的左操作数运算符应该是引用类型或可为空类型。
has compilation error, because left operand of ?? operator should be of reference or nullable type.
也许您也看过 Stackoverflow 中的这篇文章 - 这是一个优雅的
obj 样式的 null 检查。 IfNotNull(lambdaExpression)
- 如果 obj 不为 null,则返回所需的对象,否则返回 null(但不会引发异常)。如果您要访问引用的实体,我将它与实体框架一起使用,例如
返回包含在由
Entity1
引用的Entity2
中的EntityDescription
-如果任何对象Entity1
或Entity2
为null
,则为空字符串。如果没有IfNotNull
你会得到一个又长又难看的表达式。扩展方法
IfNotNull
定义如下:更新:
如果将代码更新到C# 版本 6.0(.NET Framework 4.6 - 但似乎支持较旧的框架 4. x 也),有一个新的运算符可以使此任务变得简单:“elvis”运算符
?.
。它的工作原理如下:
在这种情况下,如果
Entity2
为null
,则计算停止,并且(...)
变为null
代码> - 之后是<代码>?? string.empty 部分用string.Empty
替换null
。换句话说,它的工作方式与.IfNotNull(...)
相同。Maybe you have a look at this article in Stackoverflow too - it is an elegant null checking in the style
obj.IfNotNull(lambdaExpression)
- returning the object you want if obj is not null otherwise just null (but without throwing an exception).I used it with the Entity Framework if you're accessing a referenced entity, e.g.
which returns
EntityDescription
contained inEntity2
which is referenced byEntity1
- or an empty string if any objectEntity1
orEntity2
isnull
. WithoutIfNotNull
you would get a long and ugly expression.The extension method
IfNotNull
is defined there as follows:Update:
If you update the code to C# version 6.0 (.NET Framework 4.6 - but seems to support older frameworks 4.x too), there is a new operator available which makes this task easy: The "elvis" operator
?.
.It works as follows:
In this case, if
Entity2
isnull
, evaluation stops and(...)
becomesnull
- after which the?? string.empty
part replacesnull
bystring.Empty
. In other words, it works the same way as.IfNotNull(...)
would.foo.bar.Value 当有一个值时表示不可为 null 的值,如果没有实际值,则抛出 InvalidOperationException。
foo.bar.Value represents the non-nullable value when there is one, and throws an InvalidOperationException if there’s no real value.