C#將object對象轉換為實體對象


#region Method1

        /// <summary>
        /// 將object對象轉換為實體對象
        /// </summary>
        /// <typeparam name="T">實體對象類名</typeparam>
        /// <param name="asObject">object對象</param>
        /// <returns></returns>
        private T ConvertObject<T>(object asObject) where T : new()
        {
            //創建實體對象實例
            var t = Activator.CreateInstance<T>();
            if (asObject != null)
            {
                Type type = asObject.GetType();
                //遍歷實體對象屬性
                foreach (var info in typeof(T).GetProperties())
                {
                    object obj = null;
                    //取得object對象中此屬性的值
                    var val = type.GetProperty(info.Name)?.GetValue(asObject);
                    if (val != null)
                    {
                        //非泛型
                        if (!info.PropertyType.IsGenericType)
                            obj = Convert.ChangeType(val, info.PropertyType);
                        else//泛型Nullable<>
                        {
                            Type genericTypeDefinition = info.PropertyType.GetGenericTypeDefinition();
                            if (genericTypeDefinition == typeof(Nullable<>))
                            {
                                obj = Convert.ChangeType(val, Nullable.GetUnderlyingType(info.PropertyType));
                            }
                            else
                            {
                                obj = Convert.ChangeType(val, info.PropertyType);
                            }
                        }
                        info.SetValue(t, obj, null);
                    }
                }
            }
            return t;
        }

        #endregion
View Code

 

#region Method2

        /// <summary>
        /// 將object對象轉換為實體對象
        /// </summary>
        /// <typeparam name="T">實體對象類名</typeparam>
        /// <param name="asObject">object對象</param>
        /// <returns></returns>
        public static T ConvertObjectByJson<T>(object asObject) where T : new()
        {
            var serializer = new JavaScriptSerializer();
            //將object對象轉換為json字符
            var json = serializer.Serialize(asObject);
            //將json字符轉換為實體對象
            var t = serializer.Deserialize<T>(json);
            return t;
        }
        #endregion
View Code
        #region Method3
        /// <summary>
        /// 將object嘗試轉為指定對象
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static T ConvertObjToModel<T>(object data) where T : new()
        {
            if (data == null) return new T();
            // 定義集合    
            T result = new T();

            // 獲得此模型的類型   
            Type type = typeof(T);
            string tempName = "";

            // 獲得此模型的公共屬性 
            PropertyInfo[] propertys = result.GetType().GetProperties();
            foreach (PropertyInfo pi in propertys)
            {
                tempName = pi.Name;  // 檢查object是否包含此列    

                // 判斷此屬性是否有Setter      
                if (!pi.CanWrite) continue;

                try
                {
                    object value = GetPropertyValue(data, tempName);
                    if (value != DBNull.Value)
                    {
                        Type tempType = pi.PropertyType;
                        pi.SetValue(result, GetDataByType(value, tempType), null);

                    }
                }
                catch
                { }

            }

            return result;
        }

        /// <summary>
        /// 獲取一個類指定的屬性值
        /// </summary>
        /// <param name="info">object對象</param>
        /// <param name="field">屬性名稱</param>
        /// <returns></returns>
        public static object GetPropertyValue(object info, string field)
        {
            if (info == null) return null;
            Type t = info.GetType();
            IEnumerable<System.Reflection.PropertyInfo> property = from pi in t.GetProperties() where pi.Name.ToLower() == field.ToLower() select pi;
            return property.First().GetValue(info, null);
        }

        /// <summary>
        /// 將數據轉為制定類型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data1"></param>
        /// <returns></returns>
        public static object GetDataByType(object data1, Type itype, params object[] myparams)
        {
            object result = new object();
            try
            {
                if (itype == typeof(decimal))
                {
                    result = Convert.ToDecimal(data1);
                    if (myparams.Length > 0)
                    {
                        result = Convert.ToDecimal(Math.Round(Convert.ToDecimal(data1), Convert.ToInt32(myparams[0])));
                    }
                }
                else if (itype == typeof(double))
                {

                    if (myparams.Length > 0)
                    {
                        result = Convert.ToDouble(Math.Round(Convert.ToDouble(data1), Convert.ToInt32(myparams[0])));
                    }
                    else
                    {
                        result = double.Parse(Convert.ToDecimal(data1).ToString("0.00"));
                    }
                }
                else if (itype == typeof(Int32))
                {
                    result = Convert.ToInt32(data1);
                }
                else if (itype == typeof(DateTime))
                {
                    result = Convert.ToDateTime(data1);
                }
                else if (itype == typeof(Guid))
                {
                    result = new Guid(data1.ToString());
                }
                else if (itype == typeof(string))
                {
                    result = data1.ToString();
                }
            }
            catch
            {
                if (itype == typeof(decimal))
                {
                    result = 0;
                }
                else if (itype == typeof(double))
                {
                    result = 0;
                }
                else if (itype == typeof(Int32))
                {
                    result = 0;
                }
                else if (itype == typeof(DateTime))
                {
                    result = null;
                }
                else if (itype == typeof(Guid))
                {
                    result = Guid.Empty;
                }
                else if (itype == typeof(string))
                {
                    result = "";
                }
            }
            return result;
        } 
        #endregion
View Code

 

        #region Invoking

        /// <summary>
        /// test
        /// </summary>
        public void test()
        {
            var obj = new
            {
                id = 1,
                name = "張三",
                sex = 1,
                age = 22

            };
            //轉換
            var userModel = ConvertObject<user>(obj);
        }



        /// <summary>
        /// 用戶
        /// </summary>
        public class user
        {
            /// <summary>
            /// 編號
            /// </summary>
            public int id { set; get; }

            /// <summary>
            /// 姓名
            /// </summary>
            public string name { set; get; }

            /// <summary>
            /// 性別
            /// </summary>
            public int sex { set; get; }

            /// <summary>
            /// 年齡
            /// </summary>
            public int age { set; get; }

        }
        #endregion

 


免責聲明!

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



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