C#通过反射给对象赋值

蓝咒 提交于 2020-01-20 14:47:52
class Program
    {
        static void Main(string[] args)
        {
            UserSearchRequest model = new UserSearchRequest()
            {
                Name = "'1'=0",
                Age = 10
            };


            Type type = model.GetType();
            //var ps = type.GetProperties();

            var ps = type.GetProperties().Where(u=>u.PropertyType.FullName =="System.String").ToList();

            foreach (var p in ps)
            {
                Console.WriteLine("PropertyName:{0},Value:{1}",p.Name,p.GetValue(model,null).ToString());
                p.SetValue(model, "1001",null);
                Console.WriteLine("PropertyName:{0},Value:{1}", p.Name, p.GetValue(model, null).ToString());
            }

            Console.ReadLine();
        }
    }

    public class UserSearchRequest
    {
        public string Name { set; get; }
        public int Age { set; get; }
    }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!