【发布时间】:2023-04-03 12:58:01
【问题描述】:
我有一个从数据读取器的数据生成类类型列表的方法。
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);
有什么办法可以解决这个问题?
【问题讨论】:
-
(val1 == DBNull.Value) ? null : (int?)val1是否作为您的三元组工作? val1 的类型是 Int16 且不可为空,因此与第一个表达式中返回 null 设置的类型期望不匹配。 -
是的,它是三元的。仅当类型为 int? 时,我才会遇到此问题,否则它与小数一起使用?,日期时间?。
-
@Priya:你是如何解决这个问题的?在我的情况下,所有类型也使用相同的方法
-
你好@user2782405。这是数据类型的问题。由于我在这里使用反射,我需要指定读取器从数据库返回的相同数据类型。在数据库中它是 smallint,我试图将它转换为 int。所以它失败了。
标签: c# nullable system.reflection datareader