类型 'System.Int16' 的对象无法转换为类型"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; }

代码适用于所有属性,除了 int 学生编号。

在上面的代码中,以下行抛出ex-type '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,但您不能直接将盒装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);

当给定不同的类型时,可能会发生此错误,请检查数据库的字段类型和该表的模型文件。

相关内容

最新更新