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");
时间: 2024-10-10 04:07:44