[英]Why is ReSharper suggesting a possible NullReferenceException on a dynamic type?
If I write the following code, ReSharper is warning me for a possible NullReferenceException
. 如果我编写以下代码,ReSharper会警告我可能存在NullReferenceException
。 However I'm explicitly checking for null
in the statement above. 但是我在上面的语句中明确检查null
。 Is there something about dynamic
I do not know about (is it assuming it might be backed by a IEnumerable
or something like that)? 有什么关于dynamic
我不知道(是假设它可能由IEnumerable
或类似的东西支持)? Or is this a glitch with ReSharper? 或者这是ReSharper的故障? Or something else? 或者是其他东西?
dynamic user = connection.Query("SELECT ...").FirstOrDefault(); // Dapper Extension
if (user == null)
return null;
return new User(user.username);
// ^^^^
// (local variable) dynamic user
//
// Possible 'System.NullReferenceException'
The issue is that user == null
is a dynamic call; 问题是user == null
是一个动态调用; R# can't assume that the runtime type of the user
object will have an equality operator that works properly. R#不能假设user
对象的运行时类型将具有正常工作的相等运算符。 It could very easily have: 它很容易有:
public static bool operator ==(Foo x, Foo y) { return false; }
public static bool operator !=(Foo x, Foo y) { return true; }
in which case, user == null
would always return false
, even if the user
variable was a null
reference. 在这种情况下,即使user
变量是null
引用, user == null
也总是返回false
。
Try changing the code to: 尝试将代码更改为:
if (ReferenceEquals(user, null)) return null;
return new User(user.username);
NB: The problem only appears when you have the "Assume entity value can be null" option set to "When entity doesn't have explicit NotNull attribute". 注意:仅当“假定实体值可以为空”选项设置为“当实体没有显式的NotNull属性”时,才会出现此问题。
Try this : 试试这个 :
dynamic user = connection.Query("SELECT ...").FirstOrDefault(); // Dapper Extension
if (user != null)
return new User(user.username);
return null;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.