如何根据名称获取属性值

有没有一种方法可以根据对象的名称来获得对象属性的值?

例如:

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;
}
222624 次浏览

你得用倒影

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");
return car.GetType().GetProperty(propertyName).GetValue(car, null);

你想要反射

Type t = typeof(Car);
PropertyInfo prop = t.GetProperty("Make");
if(null != prop)
return prop.GetValue(this, null);

简单示例(客户端中没有写反射硬代码)

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

此外,其他人回答,它很容易得到属性值的 任何物体通过使用扩展方法,如:

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

对 Adam Rackis 的答案进行扩展——我们可以把扩展方法简单化如下:

public static TResult GetPropertyValue<TResult>(this object t, string propertyName)
{
object val = t.GetType().GetProperties().Single(pi => pi.Name == propertyName).GetValue(t, null);
return (TResult)val;
}

如果您愿意,也可以抛出一些错误处理。

为了避免反射,您可以将属性名设置为 Dictionary 值部分中的键和函数,这些键和函数将从请求的属性返回相应的值。