SqlParameter的构造函数编译器过载的选择 [英] SqlParameter constructor compiler overload choice
问题描述
在创建的SqlParameter
(.NET3.5)或者 OdbcParameter
,我经常使用的SqlParameter(字符串参数名称,对象的值)
构造函数重载设置的值在一个语句。
When creating an SqlParameter
(.NET3.5) or OdbcParameter
, I often use the SqlParameter(string parameterName, Object value)
constructor overload to set the value in one statement.
然而,当我试图通过文字0作为参数的值,我最初是抓住了C#编译器选择<$的(字符串,OdbcType)
过载,而不是C $ C>(字符串对象)。
However, when I tried passing a literal 0 as the value parameter, I was initially caught by the C# compiler choosing the (string, OdbcType)
overload instead of (string, Object)
.
MSDN居然发出警告这一疑难杂症在备注部分,但解释混淆了我。
MSDN actually warns about this gotcha in the remarks section, but the explanation confuses me.
为什么C#编译器决定,文字0参数应转换为 OdbcType
,而不是对象
?该警告还表示,使用 Convert.ToInt32(0)
强制对象
超负荷使用。
Why does the C# compiler decide that a literal 0 parameter should be converted to OdbcType
rather than Object
? The warning also says to use Convert.ToInt32(0)
to force the Object
overload to be used.
据混淆的说,这种转换0到一个对象类型。但不为0已经是对象类型?文字价值观的类型本页面节似乎是说文字是永远类型和 System.Object的
所以继承。
It confusingly says that this converts the 0 to an "Object type". But isn't 0 already an "Object type"? The Types of Literal Values section of this page seems to say literals are always typed and so inherit from System.Object
.
此行为似乎不是很直观。这是与魂斗罗方差或协变可能?
This behavior doesn't seem very intuitive. Is this something to do with Contra-variance or Co-variance maybe?
推荐答案
按照<一个href="http://www.microsoft.com/downloads/details.aspx?FamilyID=dfbf523c-f98c-4804-afbd-459e846b268e&displaylang=en"相对=nofollow> C#语言规范4.0 :
文字0隐式转换为 任何枚举类型。
the literal 0 implicitly converts to any enum type.
因此,的SqlParameter(参数名称,0)
解析为的SqlParameter(字符串,OdbcType)
过载。
So SqlParameter("parameterName", 0)
resolves to the SqlParameter(string, OdbcType)
overload.
如果您更改为的SqlParameter(参数名称,1)
它解析为的SqlParameter(字符串对象)
超载。同样的逻辑也适用于 Convert.ToInt32
。
If you change to SqlParameter("parameterName", 1)
it resolves to the SqlParameter(string, object)
overload. The same logic applies to Convert.ToInt32
.
这篇关于SqlParameter的构造函数编译器过载的选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!