• 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;
            }
  • 相关阅读:
    实现 HTML页面 Table 标签分页打印
    windows定时休眠设置
    python画树
    anaconda历史版本
    枚举
    is 与 as 运算符举例
    Microsoft.ACE.OLEDB.12.0报错解决方法
    winform一个带自动完成功能的TextBox
    DWZ中整合第三方jQuery(kit日历控件)插件
    asp.net 使用NPOI,泛型反射,XML导入导出excel
  • 原文地址:https://www.cnblogs.com/feiyuhuo/p/5493354.html
Copyright © 2020-2023  润新知