码迷,mamicode.com
首页 > 其他好文 > 详细

利用反射(Reflection)处理对象

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

标签:处理对象   pos   创建   read   ram   分享图片   利用   结果   type   

创建一个学生类:

 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)处理对象

标签:处理对象   pos   创建   read   ram   分享图片   利用   结果   type   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!