类型“System.Int16”的对象无法转换为类型“System.Nullable`1[System.Int32]

Pri*_*iya 6 c# nullable datareader system.reflection

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

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);
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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

public string StudentName{ get; set; }
public decimal? percentage{ get; set; }
public int? StudentNumber{ get; set; }
Run Code Online (Sandbox Code Playgroud)

代码适用于除 StudentNumber(int 型)之外的所有属性。

在上面的代码中,以下行抛出异常“System.Int16”类型的对象无法转换为“System.Nullable`1[System.Int32]”类型

info.SetValue(myobj, (val1 == DBNull.Value) ? null : val1, null);
Run Code Online (Sandbox Code Playgroud)

可以采取什么措施来解决这个问题?

Bac*_*cks 1

尝试更改类型:

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