首页 文章

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

提问于
浏览
0

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

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 回答

  • 0

    我没有'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> .

    有更好的方法,但要明确发生了什么,并在这里修复这个错误...

    info.SetValue(myobj, val1 == DBNull.Value ? null : (int?)Convert.ToInt32(val1), null);
    
  • 1

    你在这里遇到的问题是,虽然你可以将 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 .

  • 1

    尝试更改类型:

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

相关问题