有没有一种方法可以根据对象的名称来获取属性的值?
例如,如果我有:
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;
}
发布于 2011-04-01 08:45:02
return car.GetType().GetProperty(propertyName).GetValue(car, null);
发布于 2011-04-01 08:43:56
你必须使用反射
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");
发布于 2011-04-01 08:46:57
你想要反射
Type t = typeof(Car);
PropertyInfo prop = t.GetProperty("Make");
if(null != prop)
return prop.GetValue(this, null);
https://stackoverflow.com/questions/5508050
复制相似问题