为什么这个投由短到int失败? [英] Why does this cast from short to int fail?

查看:113
本文介绍了为什么这个投由短到int失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一些代码,从Microsoft Access数据库存档数据到MS SQL Server数据库。假设我们有一个数据读者已经从Access表填充,我们都在为插入准备加入一个参数一个SqlCommand,我们有失败类型转换。下面是代码:

We have some code that archives data from a Microsoft Access database into a MS SQL Server database. Assuming we have a data reader already populated from the Access table and we are adding a parameter to a SqlCommand in preparation for the insert, we have a typecast that is failing. Here is the code:

oSqlServerDbCmd_ForInsert.Parameters.AddWithValue("@Duration",
     (int) oReader["Duration"]);



从oReader领域实际上是一个整数的访问,这是在C#中的短。如果我们转换为短这里是没有问题的。但是,如果我们转换为一个int代码引发InvalidCastException。我可以从 MSDN文档被误读的:

有从短到int,长,浮动,双,或十进制预定义的隐式转换。

"There is a predefined implicit conversion from short to int, long, float, double, or decimal."

...但它听起来像这应该工作(我的推理是,如果一个隐式转换被定义为什么会一个明确的类型转换不工作?)。我认识的演员甚至没有必要的,因为AddWithValue接受一个对象,所以我们实际上已经删除了我们的代码中投,但我希望能看到一个解释,为什么这个转换是失败以防万一,我们碰上这样的事而在将来

...but it sounds like this should work (my reasoning being, if an implicit conversion is defined why would an explicit typecast not work?). I realize the cast is not even necessary because AddWithValue accepts an object, so we have actually removed the cast from our code, but I would love to see an explanation as to why this cast was failing just in case we run into something like this in the future.

推荐答案

您在你的手中是什么的unboxing 的。特别是当拆箱,你只能到拆箱最初盒装值的类型;如果该类型是A,你是拆箱到B,的它不会,如果从A到B的隐式转换存在的(拆箱仍然会失败)。

What you have in your hands is an instance of unboxing. Specifically when unboxing, you can only unbox to the type of the value that was originally boxed; if that type is A and you are unboxing to B, it does not matter if an implicit conversion from A to B exists (the unboxing will still fail).

请参阅埃里克利珀的经典博客文章对一个棘手的解释这个问题。

See Eric Lippert's classic blog post on the subject for an involved explanation.

这篇关于为什么这个投由短到int失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆