is DBNull vs. DBNull.Value.Equals()

主宰稳场 提交于 2021-02-08 13:18:17

问题


I am curious what are the pros and cons of using if(some_value is DBNull) versus if(DBNull.Value.Equals(some_value)). Personally i prefer if(some_value is DBNull) because i find it more readable. 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.


回答1:


I would go for the DBNull.Value.Equals way.

Why?

Beacuse is will check the type against equality. 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. Since there is just once instance of DBNull.Value, this check is very accurate and very fast.




回答2:


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.

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.

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.




回答3:


some_value is DbNull : checks the type of some_value against type of DBNull. This could be used if you could either instantiate an instance of DBNull OR inherit from it. 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.



来源:https://stackoverflow.com/questions/38373783/is-dbnull-vs-dbnull-value-equals

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!