繁体   English   中英

类型'System.Int16'的对象不能转换为类型'System.Nullable`1 [System.Int32]

[英]Object of type 'System.Int16' cannot be converted to type 'System.Nullable`1[System.Int32]

我有一种从数据读取器的数据生成类类型列表的方法。

   if (datareader != null && datareader .HasRows)
   {

                Dictionary<string, PropertyInfo> pDict= GetPropertyDictionary<T>();
                var fields = GetFieldNames(datareader );
                while (datareader .Read())
                {
                    T myobj= new T();
                    for (int index = 0; index < fields.Count; index++)
                    {                        
                        if (pDict.TryGetValue(fields[index], out PropertyInfo info))
                        {

                                var val1 = datareader .GetValue(index);                                
                                info.SetValue(myobj, (val1 == DBNull.Value) ? null : val1, null);

                        }
                    }

                }

            }

我有类属性,其中一些是可为空的。

public string StudentName{ get; set; }
public decimal? percentage{ get; set; }
public int? StudentNumber{ get; set; }

代码对所有属性均适用,但StudentNumber为int除外。

在上面的代码中,以下行引发'System.Int16'类型的对象对象不能转换为'System.Nullable`1 [System.Int32]类型

info.SetValue(myobj,(val1 == DBNull.Value)?null:val1,null);

如何解决这个问题?

我出于很多原因不同意此代码,但是为了解决您当前的问题并回答您的问题,这是因为您无法将Int16显式转换为Int32Nullable<Int32>int?

为此,您需要先将值转换为Int32然后转换为Nullable<Int3>

有更好的方法可以让您弄清楚发生了什么并在此处修复此错误...

info.SetValue(myobj, val1 == DBNull.Value ? null : (int?)Convert.ToInt32(val1), null);

您在这里遇到的问题是,尽管您可以将short转换为int ,但是不能直接将boxed short强制转换为int

object box = (short)5;
var x = (int?)box; // Invalid cast.
var y = (int?)(short?)box; // fine, we cast to short and then to int.

您可以将类的属性类型更改为short? ,或者您可以检查属性的类型是否为Nullable<int32>然后在这种情况下对值使用Convert.ToInt32

尝试更改类型:

var val1 = datareader.GetValue(index);    
var convertedValue = (val1 == DBNull.Value) ? null : Convert.ChangeType(val1, info.PropertyType);                            
info.SetValue(myobj, convertedValue, null);

暂无
暂无

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

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