SqlParameter 构造函数编译器重载选择
在创建 SqlParameter
(.NET3.5) 或 OdbcParameter
时,我经常使用 SqlParameter(string parameterName, Object value)
构造函数重载来设置一个语句中的值。
但是,当我尝试传递文字 0 作为值参数时,我最初被 C# 编译器捕获,选择了 (string, OdbcType)
重载而不是 (string, Object)
。
MSDN 实际上在 备注部分警告了此问题,但解释让我困惑。
为什么 C# 编译器决定将文字 0 参数转换为 OdbcType
而不是 Object
?该警告还表示使用 Convert.ToInt32(0)
强制使用 Object
重载。
它令人困惑地表示这会将 0 转换为“对象类型”。但 0 不是已经是“对象类型”了吗?此页面的 文字值类型 部分似乎说文字是总是键入,因此继承自System.Object
。
这种行为看起来不太直观。这可能与逆变或协方差有关吗?
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.
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 actually warns about this gotcha in the remarks section, but the explanation confuses me.
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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据 C# 语言规范4.0:
因此,
SqlParameter("parameterName", 0)
解析为SqlParameter(string, OdbcType)
重载。如果更改为
SqlParameter("parameterName", 1)
,它将解析为SqlParameter(string, object)
重载。相同的逻辑适用于Convert.ToInt32
。According to the C# Language Specification 4.0:
So
SqlParameter("parameterName", 0)
resolves to theSqlParameter(string, OdbcType)
overload.If you change to
SqlParameter("parameterName", 1)
it resolves to theSqlParameter(string, object)
overload. The same logic applies toConvert.ToInt32
.0 是任何枚举的默认值。因此它比对象更精确的匹配。
0 is the default value of any enum. Hence it is the more exact match than object.