Esempio n. 1
0
        private Proxy ProxyData(string json)
        {
            var argumentTable = new Dictionary <string, string>();
            var args          = json.Split(',');

            foreach (var item in args)
            {
                AddArgument(ref argumentTable, item);
            }

            var proxy = new Proxy();

            foreach (var p in proxy.GetType().GetProperties())
            {
                string value;
                if (argumentTable.TryGetValue(p.Name, out value))
                {
                    var type = p.PropertyType;
                    if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
                    {
                        var nullableConverter = new System.ComponentModel.NullableConverter(type);
                        type = nullableConverter.UnderlyingType;
                    }
                    p.SetValue(proxy, Convert.ChangeType(value, type));
                }
            }
            return(proxy);
        }
Esempio n. 2
0
        /// <summary>
        /// 转换DataTable为实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table"></param>
        /// <returns></returns>
        public static IList <T> GetEntities <T>(DataTable table) where T : new()
        {
            IList <T> entities = new List <T>();

            foreach (DataRow row in table.Rows)
            {
                T entity = new T();
                foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
                {
                    if (row.Table.Columns.Contains(propertyInfo.Name))
                    {
                        if (DBNull.Value != row[propertyInfo.Name])
                        {
                            Type type = propertyInfo.PropertyType;
                            //判断type类型是否为泛型,因为nullable是泛型类,
                            if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))//判断convertsionType是否为nullable泛型类
                            {
                                //如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
                                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(type);
                                //将type转换为nullable对的基础基元类型
                                type = nullableConverter.UnderlyingType;
                            }
                            propertyInfo.SetValue(entity, Convert.ChangeType(row[propertyInfo.Name], type), null);
                        }
                    }
                }
                entities.Add(entity);
            }
            return(entities);
        }
Esempio n. 3
0
        /// <summary>
        /// 用户信息的字段
        /// </summary>
        /// <param name="id"></param>
        /// <param name="fieldName"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public ActionResult EditField(string userId, string fieldName, string value)
        {
            User user = UserService.Instance.Get(userId);
            var  prop = typeof(User).GetProperty(fieldName);
            var  type = prop.PropertyType;

            //判断convertsionType是否为nullable泛型类
            if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
            {
                //如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(type);
                //将type转换为nullable对的基础基元类型
                type = nullableConverter.UnderlyingType;
                if (string.IsNullOrEmpty(value))
                {
                    prop.SetValue(user, null);
                }
                else
                {
                    prop.SetValue(user, Convert.ChangeType(value, type), null);
                }
            }
            else
            {
                var val = Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
                prop.SetValue(user, val);
            }
            UserService.Instance.Edit(user);
            return(Json(new { status = 0 }));
        }
        /// <summary>
        /// 类型转换(包含Nullable<>和非Nullable<>转换)
        /// </summary>
        /// <param name="value"></param>
        /// <param name="conversionType"></param>
        /// <returns></returns>
        private static object ChangeType(object value, Type conversionType)
        {
            // Note: This if block was taken from Convert.ChangeType as is, and is needed here since we're
            // checking properties on conversionType below.
            if (conversionType == null)
            {
                throw new ArgumentNullException("conversionType");
            } // end if

            // If it's not a nullable type, just pass through the parameters to Convert.ChangeType

            if (conversionType.IsGenericType &&
                conversionType.IsNullable())
            {
                if (value == null)
                {
                    return(null);
                } // end if

                // It's a nullable type, and not null, so that means it can be converted to its underlying type,
                // so overwrite the passed-in conversion type with this underlying type
                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);

                conversionType = nullableConverter.UnderlyingType;
            } // end if

            // Now that we've guaranteed conversionType is something Convert.ChangeType can handle (i.e. not a
            // nullable type), pass the call on to Convert.ChangeType
            return(Convert.ChangeType(value, conversionType));
        }
        /// <summary>
        /// DataTable转实体
        /// </summary>
        /// <typeparam name="T">实体</typeparam>
        /// <param name="table">DataTable实例</param>
        /// <returns></returns>
        public static T ToEntity <T>(this DataTable table) where T : new()
        {
            var entity = new T();

            foreach (DataRow row in table.Rows)
            {
                foreach (var item in entity.GetType().GetProperties())
                {
                    if (!row.Table.Columns.Contains(item.Name))
                    {
                        continue;
                    }
                    if (DBNull.Value == row[item.Name])
                    {
                        continue;
                    }
                    var newType = item.PropertyType;
                    //判断type类型是否为泛型,因为nullable是泛型类,
                    if (newType.IsGenericType && newType.GetGenericTypeDefinition() == typeof(Nullable <>))
                    {
                        //如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
                        var nullableConverter = new System.ComponentModel.NullableConverter(newType);
                        //将type转换为nullable对的基础基元类型
                        newType = nullableConverter.UnderlyingType;
                    }

                    item.SetValue(entity, Convert.ChangeType(row[item.Name], newType), null);
                }
            }
            return(entity);
        }
        /// <summary>
        /// DataTable to Entity
        /// </summary>
        /// <typeparam name="T">>Generic Type</typeparam>
        /// <param name="table">DataTable</param>
        /// <returns></returns>
        public static T ToEntity <T>(this DataTable table) where T : new()
        {
            T entity = new T();

            foreach (DataRow row in table.Rows)
            {
                foreach (var item in entity.GetType().GetProperties())
                {
                    if (row.Table.Columns.Contains(item.Name))
                    {
                        if (DBNull.Value != row[item.Name])
                        {
                            Type newType = item.PropertyType;

                            //(newType.IsGenericType) Determine if the type is generic because nullable is a generic class.
                            //(newType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)) Judge whether convertsionType is nullable generic class
                            if (newType.IsGenericType && newType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
                            {
                                // If the type is a nullable class, declare a NullableConverter class that provides the conversion from the Nullable class to the underlying primitive type
                                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(newType);

                                // The primitive primitive type that converts type to a nullable pair
                                newType = nullableConverter.UnderlyingType;
                            }

                            item.SetValue(entity, Convert.ChangeType(row[item.Name], newType), null);
                        }
                    }
                }
            }

            return(entity);
        }
Esempio n. 7
0
        /// <summary>
        /// 数据行对应到实体类对象
        /// </summary>
        /// <param name="row">数据行</param>
        /// <returns>实体对象</returns>
        public static T ToEntity(DataRow row)
        {
            Type type  = typeof(T);
            T    model = System.Activator.CreateInstance <T>();

            foreach (PropertyInfo pi in type.GetProperties())
            {
                if (!row.Table.Columns.Contains(pi.Name) || row[pi.Name] == null || row[pi.Name].ToString() == "")
                {
                    continue;
                }

                try
                {
                    //判断字段类型是否可以为空类型
                    if (pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
                    {
                        if (row[pi.Name] != null)
                        {
                            System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(pi.PropertyType);
                            pi.SetValue(model, Convert.ChangeType(row[pi.Name], nullableConverter.UnderlyingType), null);
                        }
                    }
                    else
                    {
                        pi.SetValue(model, Convert.ChangeType(row[pi.Name], pi.PropertyType), null);
                    }
                }
                catch
                { }
            }

            return(model);
        }
Esempio n. 8
0
 /// <summary>
 /// 获取可空类型的实际类型
 /// </summary>
 public static Type GetUnNullableType(this Type InputType)
 {
     try
     {
         string Key = InputType.Name + "-GetUnNullableType";
         if (CacheManage.Get(Key) != null)
         {
             InputType = (Type)(CacheManage.Get(Key));
         }
         else
         {
             if (InputType.IsGenericType && InputType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
             {
                 var nullableConverter = new System.ComponentModel.NullableConverter(InputType);
                 InputType = nullableConverter.UnderlyingType;
             }
             CacheManage.Insert(Key, InputType);
         }
         return(InputType);
     }
     catch (Exception ex)
     {
         ex.Data.Add("Running Process", "Super.Framework.TypeHelper.GetUnNullableType");
         ex.Data.Add("Working Parameter Type", InputType.Name);
         throw ex;
     }
 }
Esempio n. 9
0
        public static List <T> ToEntities <T>(this DataTable table) where T : new()
        {
            List <T> entities = new List <T>();

            if (table == null)
            {
                return(null);
            }
            foreach (DataRow row in table.Rows)
            {
                T entity = new T();
                foreach (var item in entity.GetType().GetProperties())
                {
                    if (table.Columns.Contains(item.Name))
                    {
                        if (DBNull.Value != row[item.Name])
                        {
                            Type newType = item.PropertyType;
                            //判断type类型是否为泛型,因为nullable是泛型类,
                            if (newType.IsGenericType &&
                                newType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))      //判断convertsionType是否为nullable泛型类
                            {
                                //如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
                                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(newType);
                                //将type转换为nullable对的基础基元类型
                                newType = nullableConverter.UnderlyingType;
                            }
                            item.SetValue(entity, Convert.ChangeType(row[item.Name], newType), null);
                        }
                    }
                }
                entities.Add(entity);
            }
            return(entities);
        }
Esempio n. 10
0
 public static Type GetUnderlyingTypeForNullable(Type nullableType)
 {
     return(_nullableTypeCache.GetOrAdd(nullableType, (nt) =>
     {
         System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(nt);
         return nullableConverter.UnderlyingType;
     }));
 }
Esempio n. 11
0
        public ActionResult Exec(ExecModel mr)
        {
            #region 动态创建类实例
            string  Typename = "Model." + mr.Type;
            dynamic obj      = System.Reflection.Assembly.Load("Model").CreateInstance(Typename, false);
            #endregion

            #region 动态解析Json
            dynamic v = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(mr.value);//{Name:张三,Age:21}
            #endregion

            #region 将类实例赋值
            System.Reflection.PropertyInfo[] fields = obj.GetType().GetProperties();//获取指定对象的所有公共属性
            foreach (System.Reflection.PropertyInfo t in fields)
            {
                Type type = t.PropertyType;
                if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))//判断convertsionType是否为nullable泛型类
                {
                    //如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
                    System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(type);
                    //将type转换为nullable对的基础基元类型
                    type = nullableConverter.UnderlyingType;
                }
                foreach (var r in v)                                                      //对json进行循环
                {
                    if (r.Name == t.Name)                                                 //判断当前属性是否在json中
                    {
                        t.SetValue(obj, Convert.ChangeType(v[t.Name].Value, type), null); //给对象赋值
                    }
                }
            }
            #endregion

            bool issuccess = false;
            if (mr.ExecType == "Update")
            {
                issuccess = BLL.CommonBLL.Update(obj);
            }
            else if (mr.ExecType == "Insert")
            {
                issuccess = BLL.CommonBLL.add(obj);
            }
            else if (mr.ExecType == "Delete")
            {
                issuccess = BLL.CommonBLL.Delete(obj);
            }
            else if (mr.ExecType == "Proc")
            {
                issuccess = BLL.CommonBLL.ExecByProc(obj);
            }

            var ret = new
            {
                messagecode = issuccess ? 1 : 0,
            };
            return(Json(ret, JsonRequestBehavior.AllowGet));
        }
Esempio n. 12
0
 /// <summary>
 /// Get a real type of  a Nullable type
 /// </summary>
 /// <param name="conversionType"></param>
 /// <returns></returns>
 public static Type GetUnNullableType(Type conversionType)
 {
     if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition() == typeof(Nullable <>))
     {
         var nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
         conversionType = nullableConverter.UnderlyingType;
     }
     return(conversionType);
 }
Esempio n. 13
0
        private static T ConvertirTipo <T>(Object valor)
        {
            Type objTipoConversion = typeof(T);

            if (objTipoConversion.IsGenericType)
            {
                objTipoConversion = new System.ComponentModel.NullableConverter(objTipoConversion).UnderlyingType;
            }
            return((T)Convert.ChangeType(valor, objTipoConversion));
        }
Esempio n. 14
0
        /// <summary>
        /// 新增博客
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task <CommonResultDto <string> > Post(BlogAddDto dto)
        {
            using (await _context.Database.BeginTransactionAsync())
            {
                System.ComponentModel.NullableConverter nullableDateTime = new System.ComponentModel.NullableConverter(typeof(DateTime?));
                string           blogContentId = Guid.NewGuid().ToString();
                string           blogId        = Guid.NewGuid().ToString();
                tbl_blog_content tbl_content   = new tbl_blog_content
                {
                    Id      = blogContentId,
                    Content = dto.Content
                };

                tbl_blog tbl_blog = new tbl_blog
                {
                    Id         = blogId,
                    Title      = dto.Title,
                    ContentId  = blogContentId,
                    Remark     = dto.Remark,
                    CategoryId = dto.CategoryId,
                    PicUrl     = dto.PicUrl,
                    ViewTimes  = 0,
                    LikeTimes  = 0,
                    State      = dto.State == "1" ? '1' : '2', //状态(枚举类型 1未发布 2已发布)
                    CreateAt   = DateTime.Now,
                    PublishAt  = dto.State == "2" ? DateTime.Now : (DateTime?)nullableDateTime.ConvertFromString(null),
                    DeleteAt   = null
                };

                List <tbl_blog_tag_relation> relationList = new List <tbl_blog_tag_relation>();
                foreach (var item in dto.TagIdList)
                {
                    relationList.Add(new tbl_blog_tag_relation
                    {
                        Id     = Guid.NewGuid().ToString(),
                        BlogId = blogId,
                        TagId  = item
                    });
                }

                await _context.tbl_blog.AddAsync(tbl_blog);

                await _context.tbl_blog_content.AddAsync(tbl_content);

                await _context.tbl_blog_tag_relation.AddRangeAsync(relationList);

                await _context.SaveChangesAsync();

                _context.Database.CommitTransaction();

                return(new CommonResultDto <string> {
                    Msg = "新增成功", Success = true
                });
            }
        }
Esempio n. 15
0
 /// <summary>
 /// ��ȡ�ɿ����͵�ʵ������
 /// </summary>
 /// <param name="conversionType"></param>
 /// <returns></returns>
 public static Type GetUnNullableType(Type conversionType)
 {
     if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
     {
         //����Ƿ��ͷ������ҷ�������ΪNullable<>����Ϊ�ɿ�����
         //��ʹ��NullableConverterת��������ת��
         var nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
         conversionType = nullableConverter.UnderlyingType;
     }
     return conversionType;
 }
Esempio n. 16
0
        /// <summary>
        /// 修改类型
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <returns></returns>
        static private Object ChangeType(object value, Type targetType)
        {
            Type convertType = targetType;

            if (targetType.IsGenericType && targetType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
            {
                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(targetType);
                convertType = nullableConverter.UnderlyingType;
            }
            return(Convert.ChangeType(value, convertType));
        }
Esempio n. 17
0
 /// <summary>
 /// 获取可空类型的实际类型
 /// </summary>
 /// <param name="conversionType"></param>
 /// <returns></returns>
 public static Type GetUnNullableType(Type conversionType)
 {
     if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
     {
         //如果是泛型方法,且泛型类型为Nullable<>则视为可空类型
         //并使用NullableConverter转换器进行转换
         var nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
         conversionType = nullableConverter.UnderlyingType;
     }
     return(conversionType);
 }
Esempio n. 18
0
        public static Type GetUnderlyingType(this Type type)
        {
            bool nullableType = type.IsGenericType &&
                                type.GetGenericTypeDefinition().Equals(typeof(Nullable <>));

            if (nullableType)
            {
                type = new System.ComponentModel.NullableConverter(type).UnderlyingType;
            }

            return(type);
        }
Esempio n. 19
0
 /// <summary>
 /// 对可空类型进行判断转换(*要不然会报错)
 /// </summary>
 /// <param name="value">DataReader字段的值</param>
 /// <param name="conversionType">该字段的类型</param>
 /// <returns></returns>
 private static object CheckType(object value, Type conversionType)
 {
     if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
     {
         if (value == null)
         {
             return(null);
         }
         System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
         conversionType = nullableConverter.UnderlyingType;
     }
     return(Convert.ChangeType(value, conversionType));
 }
Esempio n. 20
0
        public static object ChangeType2(object value, Type conversionType)
        {
            if (value is DBNull || value == null||string.IsNullOrWhiteSpace(value.ToString()))
                return null;
            if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                System.ComponentModel.NullableConverter nullableConverter
                    = new System.ComponentModel.NullableConverter(conversionType);
                conversionType = nullableConverter.UnderlyingType;
            }

            return Convert.ChangeType(value, conversionType);
        }
Esempio n. 21
0
 /// <summary>
 /// Asigna un valor a una propiedad de un objeto
 /// </summary>
 /// <typeparam name="T">Tipo de dato</typeparam>
 /// <param name="objeto">Objeto al cual se le asignara el valor a su propiedad</param>
 /// <param name="valorPropiedad">Valor de la propiedad</param>
 /// <param name="propiedad">Propiedad del objeto</param>
 /// <creador>Jonathan Contreras</creador>
 /// <fecha_creacion>23-04-2010</fecha_creacion>
 public static void AsignarValorPropiedad <T>(T objeto, Object valorPropiedad, System.Reflection.PropertyInfo propiedad)
 {
     if (propiedad != null && valorPropiedad != null && valorPropiedad.GetType() != typeof(System.DBNull))
     {
         Type objTipoConversion = propiedad.PropertyType;
         if (objTipoConversion.IsGenericType)
         {
             objTipoConversion = new System.ComponentModel.NullableConverter(objTipoConversion).UnderlyingType;
         }
         valorPropiedad = Convert.ChangeType(valorPropiedad, objTipoConversion);
         propiedad.SetValue(objeto, valorPropiedad, System.Reflection.BindingFlags.Default, null, null, null);
     }
 }
Esempio n. 22
0
        public object ChangeType(object value, Type conversionType)
        {
            if ( conversionType.IsGenericType &&
                conversionType.GetGenericTypeDefinition( ).Equals( typeof( Nullable<> ) ) ) {

                System.ComponentModel.NullableConverter nullableConverter
                    = new System.ComponentModel.NullableConverter(conversionType);

                conversionType = nullableConverter.UnderlyingType;
            }

            return Convert.ChangeType(value, conversionType);
        }
Esempio n. 23
0
        /// <summary>
        /// Metodo que permite copiar los valores de las propiedades del mismo nombre entre un DTO y otro
        /// </summary>
        /// <typeparam name="T">Tipo de dato DTO origen</typeparam>
        /// <typeparam name="X">Tipo de dato DTO destino</typeparam>
        /// <param name="datoOriginal">DTO origen</param>
        /// <param name="datoCopia">DTO destino</param>
        /// <creador>Jonathan Contreras</creador>
        /// <fecha_creacion>27-09-2010</fecha_creacion>
        public static void MapearDatos <T, X>(T datoOriginal, X datoCopia, String[] listaPropiedades)
        {
            if (datoOriginal == null || datoCopia == null)
            {
                return;
            }

            System.Reflection.PropertyInfo objPropiedadX = null, objPropiedadT = null;
            Type objTipoX = typeof(X), objTipoT = typeof(T), objTipoConversion = null;

            Object objValorOriginal = null;

            System.ComponentModel.NullableConverter objConversor = null;

            for (int intIndice = 0; intIndice < listaPropiedades.Length; intIndice++)
            {
                objPropiedadT = objTipoT.GetProperty(listaPropiedades[intIndice]);
                if (objPropiedadT != null)
                {
                    objPropiedadX = objTipoX.GetProperty(listaPropiedades[intIndice]);
                    if (objPropiedadX == null)
                    {
                        objPropiedadX = objTipoX.GetProperty(Texto.SepararTextoPorMayusculas(listaPropiedades[intIndice]).Replace(" ", "_").ToUpper());
                    }
                    if (objPropiedadX == null)
                    {
                        objPropiedadX = objTipoX.GetProperty(Texto.ConvertirAMinusculaPrimeraEnMayuscula(listaPropiedades[intIndice].ToLower().Replace("_", " ")).Replace(" ", ""));
                    }

                    if (objPropiedadX != null && objPropiedadX.CanWrite)
                    {
                        objTipoConversion = objPropiedadX.PropertyType;
                        if (objTipoConversion.IsGenericType)
                        {
                            objConversor      = new System.ComponentModel.NullableConverter(objTipoConversion);
                            objTipoConversion = objConversor.UnderlyingType;
                        }

                        if ((objValorOriginal = objPropiedadT.GetValue(datoOriginal, null)) != null)
                        {
                            objValorOriginal = Convert.ChangeType(objValorOriginal, objTipoConversion);
                            if (objValorOriginal != null)
                            {
                                objPropiedadX.SetValue(datoCopia, objValorOriginal, System.Reflection.BindingFlags.Default, null, null, null);
                            }
                        }
                    }
                }
            }
            ValidarDatosFecha <X>(ref datoCopia);
        }
        public static T CustomChangeType <T>(object value, Type conversionType)
        {
            if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                if (value == null)
                {
                    return(default(T));
                }

                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
                conversionType = nullableConverter.UnderlyingType;
            }
            return((T)Convert.ChangeType(value, conversionType));
        }
Esempio n. 25
0
        private static Type GetNullAbleProperty(Type propertyType)
        {
            var type = propertyType;

            //判断type类型是否为泛型,因为nullable是泛型类,
            if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))//判断convertsionType是否为nullable泛型类
            {
                //如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(propertyType);
                //将type转换为nullable对的基础基元类型
                type = nullableConverter.UnderlyingType;
            }
            return(type);
        }
Esempio n. 26
0
 /// <summary>
 /// 可为空类型扩展类,转换为基础类型
 /// </summary>
 /// <param name="value"></param>
 /// <param name="convertsionType"></param>
 /// <returns></returns>
 public static object ChanageType(this object value, Type convertsionType)
 {
     if (convertsionType.IsGenericType &&
         convertsionType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
     {
         if (value == null || value.ToString().Length == 0)
         {
             return(null);
         }
         System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(convertsionType);
         convertsionType = nullableConverter.UnderlyingType;
     }
     return(Convert.ChangeType(value, convertsionType));
 }
Esempio n. 27
0
        public static object ChangeType2(object value, Type conversionType)
        {
            if (value is DBNull || value == null || string.IsNullOrEmpty(value.ToString()))
            {
                return(null);
            }
            if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
            {
                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
                conversionType = nullableConverter.UnderlyingType;
            }

            return(Convert.ChangeType(value, conversionType));
        }
Esempio n. 28
0
        /// <summary>
        /// DataTable转List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static IList <T> ConvertTo <T>(DataTable dt) where T : new()
        {
            // 定义集合
            IList <T> ts = new List <T>();

            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                // 获得此模型的公共属性
                PropertyInfo[] propertys = t.GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    Type type = pi.PropertyType;
                    //if判断就是解决办法
                    if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))//判断convertsionType是否为nullable泛型类
                    {
                        //如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
                        System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(type);
                        //将type转换为nullable对的基础基元类型
                        type = nullableConverter.UnderlyingType;
                    }
                    if (dr.Table.Columns.Contains(pi.Name.ToUpper()))
                    {
                        object value = dr[pi.Name.ToUpper()];
                        if (value != DBNull.Value)
                        {
                            pi.SetValue(t, Convert.ChangeType(value, type), null);
                        }
                    }


                    //prop.SetValue(obj, value, null);

                    //tempName = pi.Name;  // 检查DataTable是否包含此列

                    //if (dt.Columns.Contains(tempName))
                    //{
                    //    // 判断此属性是否有Setter
                    //    if (!pi.CanWrite) continue;

                    //    object value = dr[tempName];
                    //    if (value != DBNull.Value)
                    //        pi.SetValue(t, value, null);
                    //}
                }
                ts.Add(t);
            }
            return(ts);
        }
Esempio n. 29
0
        private static object ChangeType(object value, Type type, bool SqlKeyWordsFilter)
        {
            string tempValue = SqlKeyWordsFilter == true?
                               Wf_RegexHelper.ParseHtmlBQ(Wf_RegexHelper.SqlKeyWordsFilter(Wf_ConvertHelper.ToString(value))) : Wf_ConvertHelper.ToString(value);

            if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
            {
                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(type);
                return(Convert.ChangeType(tempValue, nullableConverter.UnderlyingType));
            }
            else
            {
                return(Convert.ChangeType(tempValue, type));
            }
        }
        /// <summary>
        /// 对可空类型进行判断转换
        /// </summary>
        /// <param name="value">DataReader字段的值</param>
        /// <param name="conversionType">该字段的类型</param>
        /// <returns></returns>
        public static object ConvertToSpecifyType(this object value, Type conversionType)
        {
            if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                if (value == null)
                {
                    return(null);
                }
                System.ComponentModel.NullableConverter nullableConverter =
                    new System.ComponentModel.NullableConverter(conversionType);
                conversionType = nullableConverter.UnderlyingType;
            }

            return(Convert.ChangeType(value, conversionType));
        }
Esempio n. 31
0
File: Tag.cs Progetto: Panke/SDL.NET
 public T ValueAs <T>()
 {
     if (this.Value is T)
     {
         return((T)this.Value);
     }
     else
     {
         var destinationType = typeof(T);
         if (destinationType.IsNullable())
         {
             destinationType = new System.ComponentModel.NullableConverter(destinationType).UnderlyingType;
         }
         return((T)System.Convert.ChangeType(this.Value, destinationType));
     }
 }
Esempio n. 32
0
 //这个类对可空类型进行判断转换,要不然会报错
 private static object HackType(object value, Type conversionType)
 {
     if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition() == typeof(Nullable <>))
     {
         if (value == null)
         {
             return(null);
         }
         System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
         conversionType = nullableConverter.UnderlyingType;
     }
     //if (value is System.DateTime)
     //{
     //    value = Convert.ToDateTime(value).ToString("yyyyMMddHHmmss");
     //}
     return(Convert.ChangeType(value, conversionType));
 }
        public static object ChangeType(this object value, Type destinationType)
        {
            if (destinationType.IsGenericType && destinationType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                if (value == null)
                    return null;

                var nullableConverter = new System.ComponentModel.NullableConverter(destinationType);
                if (nullableConverter.CanConvertFrom(value.GetType()))
                {
                    return nullableConverter.ConvertFrom(value);
                }
                destinationType = nullableConverter.UnderlyingType;
            }

            return Convert.ChangeType(value, destinationType);
        }
Esempio n. 34
0
        private static object HackType <T>(object value, T conversionType) where T : Type
        {
            //  return value == null ? new T() : (T)value;

            value = IsNullOrDBNull(value) ? default(T) : (T)value;

            if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
            {
                if (value == null)
                {
                    return(null);
                }
                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
                conversionType = (nullableConverter.UnderlyingType as T);
            }
            return(Convert.ChangeType(value, conversionType));
        }
Esempio n. 35
0
        /// <summary>
        /// Returns an Object with the specified Type and whose value is equivalent to the specified object.
        /// Swiped from http://aspalliance.com/852_CodeSnip_ConvertChangeType_Wrapper_that_Handles_Nullable_Types
        /// </summary>
        /// <param name="value">An Object that implements the IConvertible interface.</param>
        /// <param name="conversionType">The Type to which value is to be converted.</param>
        /// <returns>An object whose Type is conversionType (or conversionType's underlying type if conversionType
        /// is Nullable&lt;&gt;) and whose value is equivalent to value. -or- a null reference, if value is a null
        /// reference and conversionType is not a value type.</returns>
        /// <remarks>
        /// This method exists as a workaround to System.Convert.ChangeType(Object, Type) which does not handle
        /// nullables as of version 2.0 (2.0.50727.42) of the .NET Framework. The idea is that this method will
        /// be deleted once Convert.ChangeType is updated in a future version of the .NET Framework to handle
        /// nullable types, so we want this to behave as closely to Convert.ChangeType as possible.
        /// This method was written by Peter Johnson at:
        /// http://aspalliance.com/author.aspx?uId=1026.
        /// </remarks>
        public static object ChangeType(object value, Type conversionType)
        {
            // Note: This if block was taken from Convert.ChangeType as is, and is needed here since we're
            // checking properties on conversionType below.
            if (conversionType == null)
            {
                throw new ArgumentNullException("conversionType");
            } // end if

            // If it's not a nullable type, just pass through the parameters to Convert.ChangeType

            if (conversionType.IsGenericType &&
              conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                // It's a nullable type, so instead of calling Convert.ChangeType directly which would throw a
                // InvalidCastException (per http://weblogs.asp.net/pjohnson/archive/2006/02/07/437631.aspx),
                // determine what the underlying type is
                // If it's null, it won't convert to the underlying type, but that's fine since nulls don't really
                // have a type--so just return null
                // Note: We only do this check if we're converting to a nullable type, since doing it outside
                // would diverge from Convert.ChangeType's behavior, which throws an InvalidCastException if
                // value is null and conversionType is a value type.
                if (value == null)
                {
                    return null;
                } // end if

                // It's a nullable type, and not null, so that means it can be converted to its underlying type,
                // so overwrite the passed-in conversion type with this underlying type
                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
                conversionType = nullableConverter.UnderlyingType;
            } // end if

            if (conversionType == typeof(System.Guid))
            {
                return new Guid(value.ToString());
            }

            // Now that we've guaranteed conversionType is something Convert.ChangeType can handle (i.e. not a
            // nullable type), pass the call on to Convert.ChangeType
            return Convert.ChangeType(value, conversionType);
        }
Esempio n. 36
0
		private void InitializeDeserializer()
		{
			if (typeof(IPathSerializable).IsAssignableFrom(BindingTargetType))
			{
				MethodInfo m = BindingTargetType.GetMethod("TryDeserializePath", BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(IPathStack), BindingTargetType }, null);
				if (m == null) throw new BindingException(String.Format("{0} is missing the static TryDeserializePath method.", BindingTargetType.FullName));
				_deserializer = delegate(IPathStack path, out object obj) {
					object[] args = new object[] { path, null };
					bool r = (bool) m.Invoke(null, args);
					obj = args[1];
					return r;
				};
			}
			else if (BindingTargetType.IsGenericType && BindingTargetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
			{
				System.ComponentModel.NullableConverter converter = new System.ComponentModel.NullableConverter(BindingTargetType);
				BindingTargetType = converter.UnderlyingType;
			}
		}
Esempio n. 37
0
        public static object ChangeType(object value, Type conversionType)
        {
            if (value == null)
                return null;
            if (conversionType.IsGenericType &&
                conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                System.ComponentModel.NullableConverter nullableConverter
                    = new System.ComponentModel.NullableConverter(conversionType);

                conversionType = nullableConverter.UnderlyingType;                
            }
            
            if (conversionType.IsEnum && value is string)
            {                
                value = Enum.Parse(conversionType, value.ToString(), true);
            }

            return Convert.ChangeType(value, conversionType);            
        }
Esempio n. 38
0
        private void ImportAttributes(IDataReader reader, string[] attributes, EntityMapping entityMapping, Entity entity, Hashtable columnAliasMapping)
        {
            if (attributes != null && _Model.GetInheritedAttributes(entity.Type).Count > 0)
            {
                ArrayList attrs = new ArrayList(attributes);
                StringCollection names = new StringCollection();

                AttributeMappingCollection attributeMappings = new AttributeMappingCollection();
                attributeMappings.TypeName = entityMapping.Type;

                // Retrieve attributes of the current entity type and all its sub classes attributes
                foreach (AttributeMapping a in entityMapping.Attributes)
                    attributeMappings.Add(a);

                IList children = _Model.GetTree(entityMapping.Type);

                if (children != null && children.Count > 0)
                {
                    foreach (Evaluant.Uss.Models.Entity e in children)
                    {
                        EntityMapping currentEM = _Mapping.Entities[e.Type];
                        if (currentEM == null)
                            throw new SqlMapperException(string.Concat("Cannot find the entity ", e.Type, " in your mapping file"));
                        foreach (Evaluant.Uss.Models.Attribute a in e.Attributes)
                        {
                            if (attributeMappings[a.Name] == null)
                                if (currentEM.Attributes[a.Name] != null)
                                    attributeMappings.Add(currentEM.Attributes[a.Name]);
                        }
                    }
                }

                foreach (AttributeMapping am in attributeMappings)
                {
                    string fullAttributeName = _Model.GetFullAttributeName(am.Name, am.ParentEntity.Type);

                    // load only specified attributes ?
                    if (((attrs.Count > 0) && !attrs.Contains(fullAttributeName)))
                        continue;

                    //Process generic Attributes
                    string name = string.Empty;
                    if (am.Discriminator != null && am.Discriminator != string.Empty)
                        if (reader[am.Discriminator] != DBNull.Value)
                            name = (string)reader[am.Discriminator];

                    if (columnAliasMapping != null && columnAliasMapping[fullAttributeName] == null)
                        continue;

                    object val = columnAliasMapping == null ? reader[fullAttributeName] : reader[columnAliasMapping[fullAttributeName].ToString()];

                    string type = (am.Discriminator != null) ? reader[am.Discriminator].ToString() : am.Name;
                    if (((type != string.Empty) && !names.Contains(type)) && (type == am.Name))
                    {
                        Type t = am.Type;

                        Evaluant.Uss.Models.Entity current = _Model.GetEntity(entity.Type);


                        if (t == null && name != null && name != string.Empty)
                            t = _Model.GetAttribute(entity.Type, name).Type;

                        string attributeName = am.Name;


                        if (t == null && entity != null && _Model.GetAttribute(entity.Type, attributeName) != null)
                            t = _Model.GetAttribute(entity.Type, attributeName).Type;

                        if (current != null && t == null)
                        {
                            while (_Model.GetParent(current) != null)
                            {
                                current = _Model.GetParent(current);
                                if (_Model.GetAttribute(current.Type, attributeName) != null)
                                    t = _Model.GetAttribute(current.Type, attributeName).Type;
                            }
                        }

                        if (current != null && t == null)
                        {
                            foreach (Evaluant.Uss.Models.Entity child in _Model.GetTree(current.Type))
                                if (_Model.GetAttribute(child.Type, attributeName) != null)
                                    t = _Model.GetAttribute(child.Type, attributeName).Type;
                        }

                        if (((t == null) || (!t.IsValueType && (t != typeof(string)))) && (am.Name == "*"))
                        {
                            object obj2 = Utils.UnSerialize((string)val);
                            t = obj2.GetType();
                        }
                        SerializableType serializable = am.GetSerializableType(am.DbType, t);

                        if (val != DBNull.Value)
                        {
                            object sValue = null;
                            switch (serializable)
                            {

                                case SerializableType.BinarySerialization:
                                    sValue = Utils.UnSerialize((byte[])val);
                                    break;
                                case SerializableType.StringSerialization:
                                    sValue = Utils.UnSerialize((string)val);
                                    t = val.GetType();

                                    break;
                                case SerializableType.Standard:
#if !EUSS11
                                    if ((t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>))))
                                    {
                                        sValue = new System.ComponentModel.NullableConverter(t).ConvertTo(val, t.GetGenericArguments()[0]);
                                    }
                                    else
#endif
                                    {
                                        if (am.DbType == DbType.String)
                                            val = ((string)val).Trim();

                                        sValue = Convert.ChangeType(val, t, CultureInfo.InvariantCulture);
                                    }
                                    break;

                                case SerializableType.String:
                                    if (val.GetType() == t)
                                        sValue = val;
                                    else
                                        sValue = Utils.StringToObject((string)val, t);
                                    break;
                                case SerializableType.Int:
                                    val = Convert.ToInt32(val);
                                    if (t.IsEnum)
                                        sValue = Enum.ToObject(t, val);
                                    else
                                        sValue = Convert.ChangeType(val, t, CultureInfo.InvariantCulture);
                                    break;

                            }

                            if (t == null)
                                t = typeof(object);

                            if (entity.FindEntry(type) == null)
                                entity.AddValue(type, sValue, t, State.UpToDate);
                        }
                        names.Add(type);
                        entity.State = State.UpToDate;
                    }
                }
            }
        }