反射修改屬性字段內容(動態轉換 DataRowToModel)

僅做學習筆記記錄使用,大牛繞行學習

 

        public T DataRowToModel<T>(DataRow row) where T : class, new()
        {

            T model = new T();

            if (row != null)
            {
                foreach (DataColumn item in row.Table.Columns)
                {
                    if (row[item.ColumnName] != null && row[item.ColumnName].ToString() != "")
                    {
                        Type type = typeof(T);
                        var list = type.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.IgnoreCase);
                        string value = row[item.ColumnName].ToString();
                        foreach (var property in list)
                        {
                            if (!property.PropertyType.IsGenericType)
                            {
                                //非泛型
                                property.SetValue(model, string.IsNullOrEmpty(value) ?
                                null : Convert.ChangeType(value, property.PropertyType), null);

                            }
                            else
                            {
                                //泛型Nullable<>
                                Type genericTypeDefinition = property.PropertyType.GetGenericTypeDefinition();
                                if (genericTypeDefinition == typeof(Nullable<>))
                                {
                                    property.SetValue(model, string.IsNullOrEmpty(value) ? null : Convert.ChangeType(value, Nullable.GetUnderlyingType(property.PropertyType)), null);
                                }
                            }
                            break;
                        }
                    }
                }
                return model;
            }
            else
            {
                return null;
            }
        }
相關文章
相關標籤/搜索