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

反射获取对象属性值和字段值

时间:2015-06-02 13:19:56      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:

ps:没什么技术含量,直接贴代码

public T GetFieldValue<T>(object obj, string name)
        {
            Type type = obj.GetType();
            System.Reflection.FieldInfo fieldInfo = type.GetField(name);
            if (fieldInfo == null)
            {
                throw new MissingFieldException(name);
            }

            object objectValue = fieldInfo.GetValue(obj);
            return (T)objectValue;
        }

        public T GetValue<T>(object obj,string name)
        {
           Type type = obj.GetType();
           System.Reflection.PropertyInfo property = type.GetProperty(name);
           if (property == null)
           {
               throw new MissingFieldException(name);
           }
      
           object objectValue = property.GetValue(obj, null);
           return (T)objectValue;
        }

调用方法

string name = this.GetFieldValue<string>(person,"Name");
int age = this.GetValue<int>(person, "Age");

 

反射获取对象属性值和字段值

标签:

原文地址:http://www.cnblogs.com/huangzelin/p/4545953.html

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