反射操作工具類


using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

namespace Framework.Utility
{
    /// <summary>
    /// 反射操作工具類
    /// </summary>
    public class ReflectionUtil
    {
        #region 根據反射機制將dataTable中指定行的數據賦給obj對象

        /// <summary>
        /// 根據反射機制將dataTable中指定行的數據賦給obj對象
        /// </summary>
        /// <param name="obj">obj對象</param>
        /// <param name="dataTable">dataTable</param>
        /// <param name="rowIndex">指定行</param>
        public static void ConvertDataRowToModel(object obj, DataTable dataTable, int rowIndex)
        {
            //指定行不存在
            if (dataTable.Rows.Count < (rowIndex + 1))
            {
                throw new Exception("指定行不存在!");
            }

            //DataTable列為空!
            if (dataTable.Columns.Count < 1)
            {
                throw new Exception("DataTable列為空!");
            }

            Type type = obj.GetType();
            PropertyInfo[] pInfos = type.GetProperties();

            try
            {
                for (int i = 0; i < dataTable.Columns.Count; i++)
                {
                    for (int j = 0; j < pInfos.Length; j++)
                    {
                        //全部轉換為小寫的作用是防止數據庫列名的大小寫和屬性的大小寫不一致
                        if (dataTable.Columns[i].ColumnName.ToLower() == pInfos[j].Name.ToLower())
                        {
                            PropertyInfo pInfo = type.GetProperty(pInfos[j].Name);  //obj某一屬性對象

                            object colValue = dataTable.Rows[rowIndex][i]; //DataTable 列值

                            #region 將列值賦給object屬性

                            if (!ObjectIsNull(colValue))
                            {
                                if (pInfos[j].PropertyType.FullName == "System.String")
                                {
                                    pInfo.SetValue(obj, Convert.ToString(colValue), null);
                                }
                                else if (pInfos[j].PropertyType.FullName == "System.Int32")
                                {
                                    pInfo.SetValue(obj, Convert.ToInt32(colValue), null);
                                }
                                else if (pInfos[j].PropertyType.FullName == "System.Int64")
                                {
                                    pInfo.SetValue(obj, Convert.ToInt64(colValue), null);
                                }
                                else if (pInfos[j].PropertyType.FullName == "System.Single")
                                {
                                    pInfo.SetValue(obj, Convert.ToSingle(colValue), null);
                                }
                                else if (pInfos[j].PropertyType.FullName == "System.Double")
                                {
                                    pInfo.SetValue(obj, Convert.ToDouble(colValue), null);
                                }
                                else if (pInfos[j].PropertyType.FullName == "System.Decimal")
                                {
                                    pInfo.SetValue(obj, Convert.ToDecimal(colValue), null);
                                }
                                else if (pInfos[j].PropertyType.FullName == "System.Char")
                                {
                                    pInfo.SetValue(obj, Convert.ToChar(colValue), null);
                                }
                                else if (pInfos[j].PropertyType.FullName == "System.Boolean")
                                {
                                    pInfo.SetValue(obj, Convert.ToBoolean(colValue), null);
                                }
                                else if (pInfos[j].PropertyType.FullName == "System.DateTime")
                                {
                                    pInfo.SetValue(obj, Convert.ToDateTime(colValue), null);
                                }
                                //可空類型
                                else if (pInfos[j].PropertyType.FullName == "System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")
                                {
                                    pInfo.SetValue(obj, Convert.ToDateTime(colValue), null);
                                }
                                else if (pInfos[j].PropertyType.FullName == "System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")
                                {
                                    pInfo.SetValue(obj, Convert.ToDateTime(colValue), null);
                                }
                                else if (pInfos[j].PropertyType.FullName == "System.Nullable`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")
                                {
                                    pInfo.SetValue(obj, Convert.ToInt32(colValue), null);
                                }
                                else if (pInfos[j].PropertyType.FullName == "System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")
                                {
                                    pInfo.SetValue(obj, Convert.ToInt32(colValue), null);
                                }
                                else if (pInfos[j].PropertyType.FullName == "System.Nullable`1[[System.Int64, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")
                                {
                                    pInfo.SetValue(obj, Convert.ToInt64(colValue), null);
                                }
                                else if (pInfos[j].PropertyType.FullName == "System.Nullable`1[[System.Int64, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")
                                {
                                    pInfo.SetValue(obj, Convert.ToInt64(colValue), null);
                                }
                                else if (pInfos[j].PropertyType.FullName == "System.Nullable`1[[System.Decimal, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")
                                {
                                    pInfo.SetValue(obj, Convert.ToDecimal(colValue), null);
                                }
                                else if (pInfos[j].PropertyType.FullName == "System.Nullable`1[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")
                                {
                                    pInfo.SetValue(obj, Convert.ToDecimal(colValue), null);
                                }
                                else if (pInfos[j].PropertyType.FullName == "System.Nullable`1[[System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")
                                {
                                    pInfo.SetValue(obj, Convert.ToBoolean(colValue), null);
                                }
                                else if (pInfos[j].PropertyType.FullName == "System.Nullable`1[[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")
                                {
                                    pInfo.SetValue(obj, Convert.ToBoolean(colValue), null);
                                }
                                else
                                {
                                    throw new Exception("屬性包含不支持的數據類型!");
                                }
                            }
                            else
                            {
                                pInfo.SetValue(obj, null, null);
                            }

                            #endregion 將列值賦給object屬性

                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //LogTxt.LogException(ex.Message + "\r\n" + ex.Source + "\r\n" + ex.TargetSite + "\r\n" + ex.StackTrace + "\r\n");
                throw ex;
            }
        }

        #endregion 根據反射機制將dataTable中指定行的數據賦給obj對象

        #region 根據反射機制從obj對象取值並用該值添加datatable行

        /// <summary>
        /// 根據反射機制從obj對象取值並用該值添加datatable行
        /// </summary>
        /// <param name="obj">obj對象</param>
        /// <param name="dataTable">dataTable</param>
        /// <param name="rowIndex">指定行</param>
        public static void ConvertModelToNewDataRow(object obj, DataTable dataTable, int rowIndex)
        {
            //DataTable列為空!
            if (dataTable.Columns.Count < 1)
            {
                throw new Exception("DataTable列為空!");
            }

            DataRow dr = dataTable.NewRow();
            Type type = obj.GetType();
            PropertyInfo[] pInfos = type.GetProperties();

            try
            {
                for (int i = 0; i < dataTable.Columns.Count; i++)
                {
                    for (int j = 0; j < pInfos.Length; j++)
                    {
                        //全部轉換為小寫的作用是防止數據庫列名的大小寫和屬性的大小寫不一致
                        if (dataTable.Columns[i].ColumnName.ToLower() == pInfos[j].Name.ToLower())
                        {
                            PropertyInfo pInfo = type.GetProperty(pInfos[j].Name);

                            object beanValue = pInfo.GetValue(obj, null);

                            //將bean中屬性值賦給datarow
                            if (!ObjectIsNull(beanValue))
                            {
                                dr[i] = beanValue;
                            }
                            else
                            {
                                dr[i] = DBNull.Value;
                            }
                            break;
                        }
                    }
                }

                dataTable.Rows.InsertAt(dr, rowIndex);
                dataTable.AcceptChanges();
            }
            catch (Exception ex)
            {
                //LogTxt.LogException(ex.Message + "\r\n" + ex.Source + "\r\n" + ex.TargetSite + "\r\n" + ex.StackTrace + "\r\n");
                throw ex;
            }
        }

        #endregion 根據反射機制從obj對象取值並用該值添加datatable行

        #region 根據反射機制從obj對象取值並賦給datatable的指定行

        /// <summary>
        /// 根據反射機制從obj對象取值並賦給datatable的指定行
        /// </summary>
        /// <param name="obj">obj對象</param>
        /// <param name="dataTable">dataTable</param>
        /// <param name="rowIndex">指定行</param>
        public static void ConvertModelToSpecDataRow(object obj, DataTable dataTable, int rowIndex)
        {
            //指定行不存在
            if (dataTable.Rows.Count < (rowIndex + 1))
            {
                throw new Exception("指定行不存在!");
            }

            //DataTable列為空!
            if (dataTable.Columns.Count < 1)
            {
                throw new Exception("DataTable列為空!");
            }

            Type type = obj.GetType();
            PropertyInfo[] pInfos = type.GetProperties();

            try
            {
                for (int i = 0; i < dataTable.Columns.Count; i++)
                {
                    for (int j = 0; j < pInfos.Length; j++)
                    {
                        //全部轉換為小寫的作用是防止數據庫列名的大小寫和屬性的大小寫不一致

                        if (dataTable.Columns[i].ColumnName.ToLower() == pInfos[j].Name.ToLower())
                        {
                            PropertyInfo pInfo = type.GetProperty(pInfos[j].Name);
                            object beanValue = pInfo.GetValue(obj, null);

                            //將bean中屬性值賦給datarow
                            if (!ObjectIsNull(beanValue))
                            {
                                dataTable.Rows[rowIndex][i] = beanValue;
                            }
                            else
                            {
                                dataTable.Rows[rowIndex][i] = DBNull.Value;
                            }
                            break;
                        }
                    }
                }
                dataTable.AcceptChanges();
            }
            catch (Exception ex)
            {
                //LogTxt.LogException(ex.Message + "\r\n" + ex.Source + "\r\n" + ex.TargetSite + "\r\n" + ex.StackTrace + "\r\n");
                throw ex;
            }
        }

        #endregion 根據反射機制從obj對象取值並賦給datatable的指定行

        #region 根據對象名返回類實例

        /// <summary>
        /// 根據對象名返回類實例
        /// </summary>
        /// <param name="parObjectName">對象名稱</param>
        /// <returns>對象實例(可強制轉換為對象實例)</returns>
        public static object GetObjectByObjectName(string parObjectName)
        {
            Type t = Type.GetType(parObjectName); //找到對象
            return System.Activator.CreateInstance(t);         //實例化對象
        }

        #endregion 根據對象名返回類實例

        #region 判斷對象是否為空

        /// <summary>
        /// 判斷對象是否為空
        /// </summary>
        /// <param name="obj">對象</param>
        /// <returns></returns>
        static public bool ObjectIsNull(Object obj)
        {
            //如果對象引用為null 或者 對象值為null 或者對象值為空
            if (obj == null || obj == DBNull.Value || obj.ToString().Equals("") || obj.ToString() == "")
            {
                return true;
            }
            return false;
        }

        #endregion 判斷對象是否為空

        #region 根據反射機制將DataTable轉換為實體集合。

        /// <summary>
        /// 根據反射機制將DataTable轉換為實體集合。
        /// </summary>
        /// <typeparam name="T">實體類型。</typeparam>
        /// <param name="dt">DataTable。</param>
        /// <returns>實體集合。</returns>
        public static List<T> ConvertDataTableToModelList<T>(DataTable dt)
        {
            if (dt == null)
            {
                return null;
            }
            List<T> result = new List<T>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                T t = Activator.CreateInstance<T>();
                ConvertDataRowToModel(t, dt, i);
                result.Add(t);
            }
            return result;
        }

        #endregion 根據反射機制將DataTable轉換為實體集合。

        /// <summary>
        /// 通用(調用對象方法前先new一遍對象,故對象的狀態無法保留;無用有無參構造函數,並調用無參方法),
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="methodName"></param>
        public static void InvokeMethod<T>(string methodName, object[] param = null) where T : new()
        {
            T instance = new T();
            MethodInfo method = typeof(T).GetMethod(methodName);
            method.Invoke(instance, param);
        }

        /// <summary>
        /// 調用一個具體實例對象的方法,會保留對象狀態
        /// </summary>
        /// <param name="o"></param>
        /// <param name="methodName"></param>
        public static void InvokeMethod(object o, string methodName, object[] param = null)
        {
            o.GetType().GetMethod(methodName).Invoke(o, param);
        }
    }
}

 


免責聲明!

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



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