[英]Any way how to force Equals to return false instead of Null reference exception?
I ran into a null reference exception on line: 我在线遇到了一个空引用异常:
dr["IsSandpit"] = p.MineralName.Equals("Sand");
Of course the fix is: 当然修复是:
dr["IsSandpit"] = p.MineralName!=null && p.MineralName.Equals("Sand");
But I am wondering if a nullable type can be configured that the Equals method instead of throwing a null reference exception would just return false
for a strongly typed variable? 但我想知道是否可以配置一个可空类型,Equals方法而不是抛出空引用异常只会为强类型变量返回
false
? Or some method NotNullAndEquals
? 或者某些方法
NotNullAndEquals
?
Null in the database means something like "not filled" or empty and "empty" surely is not equal to "Sand". 数据库中的空表示“未填充”或空“空”,“空”肯定不等于“沙”。 (Perhaps this is a duplicate but I have not found the right question)
(也许这是重复但我没有找到正确的问题)
You can call the static Equals
method on both operands: 您可以在两个操作数上调用静态
Equals
方法:
var isEqual = string.Equals("Sand", p.MineralName); // return false for null.
This will remove the need to access a potentially null reference. 这将消除访问可能为空的引用的需要。 Alternately, you can use the null propagation operator to avoid the operation if the value is null:
或者,如果值为null,则可以使用null传播运算符来避免操作:
var isEqual = p.MineralName?.Equals("Sand"); // return null for null.
These are much better approaches, IMO, than using extension methods to hack together a method that can theoretically be called on a null reference, since that approach leads to confusion on whether you can safely call a method without checking for null. 这些是更好的方法,IMO,比使用扩展方法来破解理论上可以在空引用上调用的方法,因为这种方法会导致混淆是否可以安全地调用方法而不检查null。 Imagine this code:
想象一下这段代码:
if (!p.MineralName.Equals("Sand"))
{
return p.MineralName.ToUpper(); // throws NullReferencException!
}
The expression 表达方式
p.MineralName?.Equals("Sand")
will evaluate to null
if p.MineralName
is null. 将计算为
null
,如果p.MineralName
为null。 You can then coalesce it to false, like so: 然后,您可以将其合并为false,如下所示:
p.MineralName?.Equals("Sand") ?? false
As an option you can utilize a self-created NotNullAndEquals extension method: 作为选项,您可以使用自创的NotNullAndEquals扩展方法:
public static class Utilities {
public static bool NotNullAndEquals(this string value, string expected) {
return value != null && value.Equals(expected);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.