我有一个从数据读取器的数据生成类类型列表的方法 .
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)之外的所有属性 .
在上面的代码行抛出exeption Object of type 'System.Int16' cannot be converted to type 'System.Nullable`1[System.Int32] :
info.SetValue(myobj,(val1 == DBNull.Value)?null:val1,null);
可以做些什么来解决这个问题?
3 回答
我没有't agree with this code for many reasons but to solve your current problem and answer your question it'因为你无法将
Int16
显式转换为Int32
,也不能转换为Nullable<Int32>
或int?
.要实现这一点,您需要先将值转换为
Int32
,然后再转换为Nullable<Int3>
.有更好的方法,但要明确发生了什么,并在这里修复这个错误...
你在这里遇到的问题是,虽然你可以将
short
强制转换为int
,但你不能直接将盒装的short
强制转换为int
. 即您可以将类的属性类型更改为
short?
,或者您可以检查属性的类型是否为Nullable<int32>
,并在该情况下使用Convert.ToInt32
.尝试更改类型: