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

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

 

posted @ 2015-06-02 11:24  玻璃鱼儿  阅读(1319)  评论(1编辑  收藏  举报