• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
欢迎来到小佳的世界
博客园    首页    新随笔    联系   管理     

C#利用反射给Model 的可空字段赋值

Main

public static void Main(string[] args)
        {
            var list = new List<string>();
            list.Add("1");
            list.Add("Tom");
            list.Add("");
            list.Add("1234@sss");

            var model = new TestModel();

            var properties = model.GetType().GetProperties();

            for (int i = 0; i < properties.Count(); i++)
            {
                var type = properties[i].PropertyType;

                if (type.IsGenericType && type.GetGenericTypeDefinition() ==  typeof(Nullable<>))
                {
                    if (string.IsNullOrEmpty(list[i]))
                    {
                        properties[i].SetValue(model, null, null);
                        continue;
                    }
                    type = Nullable.GetUnderlyingType(type);
                }

                properties[i].SetValue(model, Convert.ChangeType(list[i], type), null);
            }

            Console.ReadKey();
        }

Model

    public class TestModel
    {
        public int No { get; set; }

        public string Name { get; set; }

        public int? Age { get; set; }

        public string Email { get; set; }
    }

 

  

努力的小佳
posted @ 2020-08-01 16:22  jx++  阅读(590)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3