如何获得基于名称的属性值
有没有办法根据其名称获取对象属性的值?
例如,如果我有:
public class Car : Vehicle { public string Make { get; set; } }
和
var car = new Car { Make="Ford" };
我想写一个方法,我可以传入属性名称,它会返回属性值。 即:
public string GetPropertyValue(string propertyName) { return the value of the property; }
return car.GetType().GetProperty(propertyName).GetValue(car, null);
你必须使用reflection
public object GetPropertyValue(object car, string propertyName) { return car.GetType().GetProperties() .Single(pi => pi.Name == propertyName) .GetValue(car, null); }
如果你想成为一个真正的幻想,你可以把它作为一个扩展方法:
public static object GetPropertyValue(this object car, string propertyName) { return car.GetType().GetProperties() .Single(pi => pi.Name == propertyName) .GetValue(car, null); }
接着:
string makeValue = (string)car.GetPropertyValue("Make");
你想要反思
Type t = typeof(Car); PropertyInfo prop = t.GetProperty("Make"); if(null != prop) return prop.GetValue(this, null);
简单的示例(在客户端没有写入reflection硬代码)
class Customer { public string CustomerName { get; set; } public string Address { get; set; } // approach here public string GetPropertyValue(string propertyName) { try { return this.GetType().GetProperty(propertyName).GetValue(this, null) as string; } catch { return null; } } } //use sample static void Main(string[] args) { var customer = new Customer { CustomerName = "Harvey Triana", Address = "Something..." }; Console.WriteLine(customer.GetPropertyValue("CustomerName")); }
另外其他人回答,它的Easy可以通过使用扩展方法获得任何对象的属性值,如:
public static class Helper { public static object GetPropertyValue(this object T, string PropName) { return T.GetType().GetProperty(PropName) == null ? null : T.GetType().GetProperty(PropName).GetValue(T, null); } }
用法是:
Car foo = new Car(); var balbal = foo.GetPropertyValue("Make");