C#泛型轉換函數



public static IList <T> ConvertToList< T>(DataTable dt) where T : new() { List<T > list = new List< T>(); T model = default (T); foreach (DataRow dr in dt.Rows) { model = Activator.CreateInstance<T >(); PropertyInfo[] propertys = model.GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { if (dt.Columns.Contains(pi.Name)) { if (!pi.CanWrite) continue ; object value = dr[pi.Name]; if (value != DBNull .Value) { pi.SetValue(model, value, null); } else { pi.SetValue(model, null, null ); } } } list.Add(model); } return list; } public static DataTable ToDataTable< T>(IEnumerable <T> list) { List<PropertyInfo > pList = new List< PropertyInfo>(); Type type = typeof (T); DataTable dt = new DataTable(); Array.ForEach<PropertyInfo >(type.GetProperties(), p => { pList.Add(p); Type colType = p.PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof( Nullable<>))) { colType = colType.GetGenericArguments()[0]; } dt.Columns.Add(p.Name, colType); }); foreach (var item in list) { DataRow row = dt.NewRow(); pList.ForEach(p => row[p.Name] = p.GetValue(item, null) == null ? DBNull.Value : p.GetValue(item, null)); dt.Rows.Add(row); } return dt; }



       /// <summary>
        /// C#系統類型轉換為SQL數據庫類型
        /// </summary>
        /// <param name=" theType"></param>
        /// <returns></returns>
        public static SqlDbType GetDBType(System. Type theType)
        {
            System.Data.SqlClient. SqlParameter p1;
            System.ComponentModel. TypeConverter tc;
            p1 = new System.Data.SqlClient.SqlParameter ();
            tc = System.ComponentModel. TypeDescriptor.GetConverter(p1.DbType);
            if (tc.CanConvertFrom(theType))
            {
                p1.DbType = ( DbType)tc.ConvertFrom(theType.Name);
            }
            else
            {
                //Try brute force
                try
                {
                    p1.DbType = ( DbType)tc.ConvertFrom(theType.Name);
                }
                catch (Exception )
                {
                    //Do Nothing; will return NVarChar as default
                }
            }
            return p1.SqlDbType;
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM