简体   繁体   English

无效的转换异常从smallint转换为Int32时?

[英]Invalid Cast Exception While converting from smallint to Int32?

The code below fills the properties of my model from the DataReader .I made some properties Nullable and it isn't working since then. 下面的代码从DataReader填充了我的模型的属性。我使一些属性为Nullable ,从那时起它就不起作用了。

foreach (var property in _properties)
{
    property.SetValue(model, null, null);

    if (columnsInDataReader.Contains(property.Name.ToLower()))
    {
        if (!(_dataReader[property.Name] == DBNull.Value))
            property.SetValue(model, _dataReader[property.Name]);
    }
}

The property is Int32? 该属性是Int32? and the database column is smallint and the conversion fails. 并且数据库smallint ,并且转换失败。

Even if an implicit conversion from short to int? 即使从shortint? 隐式转换 int? do exists, the issue here arises from the fact that the data reader returns a boxed short , for which you need an unboxing conversion . 确实存在,这里的问题是由于数据读取器返回一个装箱的 short ,而您需要进行拆箱转换 In this specific case, the conversion is from object to a value type ( int? ). 在这种特定情况下,转换是从object到值类型( int? )的。

The paragraph that matches your situation is the last of the cited section: since the object returned is a boxed short and not a boxed int , the cast fails. 符合您情况的段落是引用部分的最后:由于返回的对象是装箱的short而不是装箱的int ,因此强制转换失败。

As a concrete example, compare these two snippets: 作为一个具体的示例,比较以下两个片段:

short src = 42;
int? dst = (int?)src;

object src = (short)42;
int? dst = (int?)src;

While the first one succeeds, the second throws an InvalidCastException . 当第一个成功时,第二个抛出InvalidCastException

In your case, no explicit cast occurs, however the call to SetValue applies similar conversion rules, and therefore fails. 在您的情况下,不会发生显式SetValue转换,但是对SetValue的调用将应用类似的转换规则,因此会失败。

Summing up, in order to have the call succeed, you must choose the type of the property among those that are castable at runtime from the type of the extracted object, such as short and short? 总结起来,为了使调用成功,您必须从提取的对象的类型(例如shortshort?选择在运行时可转换的属性的类型short? .

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

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