首页 > 其他 > 详细

利用反射(Reflection)处理对象

时间:2018-04-03 18:56:46      阅读:200      评论:0      收藏:0      [点我收藏+]

创建一个学生类:

 public class Student
    {
        public int Id { set; get; }
        public string Name { set; get; }
        public string Sex { set; get; }
        public int Age { set; get; }
    }

创建一个处理数据的类:

 public class Deal<T> where T : class
    {
        public T DealModel(T model)
        {
            var list=model.GetType().GetProperties();
            foreach (var item in list)
            {
                if (typeof(int) == item.PropertyType) //判断是否为int类型
                    item.SetValue(model, (int)item.GetValue(model) + 1);
                if (typeof(string) == item.PropertyType) //判断是否为string
                    item.SetValue(model, (string)item.GetValue(model) + "123");
            }
            return model;
        }

运行:

class Program
    {
        static void Main(string[] args)
        {
//创建一个学生
  var stu = new Student
            {
                Age = 11,
                Id = 1001,
                Name = "张三",
                Sex = ""
            };

//处理前的stu Console.WriteLine("\t{0}\t{1}\t{2}\t{3}",stu.Id,stu.Name,stu.Sex,stu.Age);
//处理学生对象

var deal=new Deal<Student>();
stu =deal.DealModel(stu);
//处理后的stu
Console.WriteLine("\t{0}\t{1}\t{2}\t{3}",stu.Id,stu.Name,stu.Sex,stu.Age);

Console.ReadKey();
} }

结果stu中的int类型数据增加1,string类型数据追加字符"123";

技术分享图片

 

利用反射(Reflection)处理对象

原文:https://www.cnblogs.com/Arvin-Ou/p/8710236.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!