C#类型“System.Int64”的对象无法转换为类型“System.Int32”

2018-11-26 17:22:22 阅读量:1408,日阅读:1,周阅读:4,月阅读:16 0条

前几天开发个c#小项目,win7 64/win10 64 都通过了,在服务器2012上面一直提示:

DataTable转换为List<T>对象遇到问题:类型“System.Int64”的对象无法转换为类型“System.Int32”

百度了下,找了个函数,记录一下。

 

/// <summary>
/// 利用反射将DataTable转换为List<T>对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static List <T> DataTableToList <T> (DataTable dt) where T: class, new()
{
    Type t = typeof(T);
    PropertyInfo[] propertys = t.GetProperties();
    List <T> list = new List <T> ();
    string typeName = string.Empty;
    foreach(DataRow dr in dt.Rows)
    {
        T o = new T();
        foreach(PropertyInfo pi in propertys)
        {
            typeName = pi.Name;
            if(dt.Columns.Contains(typeName))
            {
                if(!pi.CanWrite)
                {
                    continue;
                }
                object value = dr[typeName];
                if(value == DBNull.Value)
                {
                    continue;
                }
                if(pi.PropertyType == typeof(string))
                {
                    pi.SetValue(o, value.ToString(), null);
                }
                else if(pi.PropertyType == typeof(int) || pi.PropertyType == typeof(int ? ))
                {
                    pi.SetValue(o, int.Parse(value.ToString()), null);
                }
                else if(pi.PropertyType == typeof(DateTime ? ) || pi.PropertyType == typeof(DateTime))
                {
                    pi.SetValue(o, DateTime.Parse(value.ToString()), null);
                }
                else if(pi.PropertyType == typeof(float))
                {
                    pi.SetValue(o, float.Parse(value.ToString()), null);
                }
                else if(pi.PropertyType == typeof(double))
                {
                    pi.SetValue(o, double.Parse(value.ToString()), null);
                }
                else
                {
                    pi.SetValue(o, value, null);
                }
            }
        }
        list.Add(o);
    }
    return list;
}
标签: DataTable List C#

非特殊说明,本博所有文章均为博主原创。

请使用[QQ登录]后进行评论