如何根据名称获取属性值 [英] How to get a property value based on the name
本文介绍了如何根据名称获取属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法根据名称获取对象的属性值?
is there a way to get the value of a property of a object based on its name?
例如,如果我有:
public class Car : Vehicle
{
public string Make { get; set; }
}
和
var car = new Car { Make="Ford" };
我想编写一个方法,我可以在其中传入属性名称并返回属性值.即:
I want to write a method where I can pass in the property name and it would return the property value. ie:
public string GetPropertyValue(string propertyName)
{
return the value of the property;
}
推荐答案
return car.GetType().GetProperty(propertyName).GetValue(car, null);
这篇关于如何根据名称获取属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文