[英]Object of type 'System.Int16' cannot be converted to type 'System.Nullable`1[System.Int32]
I've a method that generates list of class type from data of data reader. 我有一种从数据读取器的数据生成类类型列表的方法。
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);
}
}
}
}
I have class properties, some of them are nullable. 我有类属性,其中一些是可为空的。
public string StudentName{ get; set; }
public decimal? percentage{ get; set; }
public int? StudentNumber{ get; set; }
Code works properly for all properties except StudentNumber which is int. 代码对所有属性均适用,但StudentNumber为int除外。
In above code following line throws exeption Object of type 'System.Int16' cannot be converted to type 'System.Nullable`1[System.Int32] : 在上面的代码中,以下行引发'System.Int16'类型的对象对象不能转换为'System.Nullable`1 [System.Int32]类型 :
info.SetValue(myobj, (val1 == DBNull.Value) ? null : val1, null);
info.SetValue(myobj,(val1 == DBNull.Value)?null:val1,null);
What can be done to solve this issue? 如何解决这个问题?
I don't agree with this code for many reasons but to solve your current problem and answer your question it's because you can't explicitly convert Int16
to Int32
nor to Nullable<Int32>
or int?
我出于很多原因不同意此代码,但是为了解决您当前的问题并回答您的问题,这是因为您无法将
Int16
显式转换为Int32
或Nullable<Int32>
或int?
. 。
To make this happen you need to first convert the value to Int32
then to Nullable<Int3>
. 为此,您需要先将值转换为
Int32
然后转换为Nullable<Int3>
。
There are better ways but to make it clear what's going on and to fix this one error here you go... 有更好的方法可以让您弄清楚发生了什么并在此处修复此错误...
info.SetValue(myobj, val1 == DBNull.Value ? null : (int?)Convert.ToInt32(val1), null);
The problem that you're having here is that, while you can cast a short
to an int
, you can't cast a boxed short
to an int
directly. 您在这里遇到的问题是,尽管您可以将
short
转换为int
,但是不能直接将boxed short
强制转换为int
。 ie, 即
object box = (short)5;
var x = (int?)box; // Invalid cast.
var y = (int?)(short?)box; // fine, we cast to short and then to int.
You could change the property type of your class to short?
您可以将类的属性类型更改为
short?
, or you could check if your property's type is Nullable<int32>
and use Convert.ToInt32
on the value under that situation. ,或者您可以检查属性的类型是否为
Nullable<int32>
然后在这种情况下对值使用Convert.ToInt32
。
Try to change type: 尝试更改类型:
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.