利用反射(Reflection)处理对象

创建一个学生类:

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

 

posted @ 2018-04-03 18:20  一条大咸鱼啊  阅读(221)  评论(0编辑  收藏  举报