简体   繁体   English

是DBNull与DBNull.Value.Equals()

[英]is DBNull vs. DBNull.Value.Equals()

I am curious what are the pros and cons of using if(some_value is DBNull) versus if(DBNull.Value.Equals(some_value)) . 我很好奇使用if(some_value is DBNull)if(DBNull.Value.Equals(some_value))的优缺点是什么。 Personally i prefer if(some_value is DBNull) because i find it more readable. 我个人更喜欢if(some_value is DBNull)因为我发现它更具可读性。 I know Microsoft recommends using if(DBNull.Value.Equals(some_value)) according to https://msdn.microsoft.com/en-us/library/system.dbnull%28v=vs.110%29.aspx . 我知道微软建议根据https://msdn.microsoft.com/en-us/library/system.dbnull%28v=vs.110%29.aspx使用if(DBNull.Value.Equals(some_value))

I would go for the DBNull.Value.Equals way. 我会选择DBNull.Value.Equals方式。

Why? 为什么?

Beacuse is will check the type against equality. 怎么一回事,因为is将检查对平等的类型。 It has to look up the left hand type and match that against the right hand type which it also has to look up. 它必须查找左手类型并将其与右手类型匹配,它也必须查找。 After that it can compare the types, most likely by checking for reference equality. 之后,它可以比较类型,最有可能通过检查参考相等性。

That would be less efficient than just checking reference equality, which DBNull.Value.Equals does. 这比检查DBNull.Value.Equals所做的引用相等性效率低。 Since there is just once instance of DBNull.Value , this check is very accurate and very fast. 由于只有一次DBNull.Value实例,因此该检查非常准确且非常快。

value is DBNull actually checks whether value is an instance of the DBNull class, while value == DBNull.Value actually performs a reference comparison between value and the only instance of the singleton class DBNull . value is DBNull实际上检查value是否是DBNull类的实例,而value == DBNull.Value实际上执行value与单例类DBNull的唯一实例之间的引用比较。

The value is DBNull checks whether value is an instance of DBNull , which is only possible if value == DBNull.Value , since DBNull is a singleton. value is DBNull检查是否value是的一个实例DBNull ,这是唯一可能的,如果value == DBNull.Value ,由于DBNull是一个单。

The advantage of using value == DBNull.Value is that it does a direct reference comparison which will be more efficient than determining the types for the is DBNull comparison. 使用value == DBNull.Value的优点是它进行直接引用比较,这比确定is DBNull比较的类型更有效。

some_value is DbNull : checks the type of some_value against type of DBNull . some_value is DbNull :根据DBNull类型检查some_value的类型。 This could be used if you could either instantiate an instance of DBNull OR inherit from it. 如果您可以实例化DBNull的实例或从中继承,则可以使用此方法。 But no, this class has private constructors and is sealed. 但不,这个类有私有构造函数并且是密封的。

DBNull.Value.Equals(some_value) : checks value of some_value against the value represented by DBNull.Value . DBNull.Value.Equals(some_value)针对由所表示的值的SOME_VALUE检查 DBNull.Value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM