C#通過反射給對象賦值


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; }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM