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

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-02-27
  • 2022-12-23
  • 2022-02-17
  • 2021-08-21
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-21
  • 2021-07-05
  • 2021-11-10
  • 2022-12-23
  • 2022-01-17
相关资源
相似解决方案