C# 利用反射动态将字符串转换成属性对应的类型值

在开发的过程中,我们经常要用到属性的绑定,我们可以通过反射来做。

        /// <summary>
        /// 为指定对象分配参数
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="dic">字段/值</param>
        /// <returns></returns>
        public static T Assign<T>(Dictionary<string, string> dic) where T : new()
        {
            Type myType = typeof(T);
            T entity = new T();
            var fields = myType.GetProperties();
            string val = string.Empty;
            object obj = null;

            foreach (var field in fields)
            {
                if (!dic.Keys.Contains(field.Name))
                    continue;
                val = dic[field.Name];

                object defaultVal;
                if (field.PropertyType.Name.Equals("String"))
                    defaultVal = "";
                else if (field.PropertyType.Name.Equals("Boolean"))
                {
                    defaultVal = false;
                    val = (val.Equals("1") || val.Equals("on")).ToString();
                }
                else if (field.PropertyType.Name.Equals("Decimal"))
                    defaultVal = 0M;
                else
                    defaultVal = 0;

                if (!field.PropertyType.IsGenericType)
                    obj = string.IsNullOrEmpty(val) ? defaultVal : Convert.ChangeType(val, field.PropertyType);
                else
                {
                    Type genericTypeDefinition = field.PropertyType.GetGenericTypeDefinition();
                    if (genericTypeDefinition == typeof(Nullable<>))
                        obj = string.IsNullOrEmpty(val) ? defaultVal : Convert.ChangeType(val, Nullable.GetUnderlyingType(field.PropertyType));
                }

                field.SetValue(entity, obj, null);
            }

            return entity;
        }

 

 

出处:https://www.cnblogs.com/feiyuhuo/p/5493354.html

posted on 2019-02-20 15:21  jack_Meng  阅读(1428)  评论(0编辑  收藏  举报

导航