C# 如何基于名称获取属性值
有没有办法根据对象的名称获取其属性的值 例如,如果我有:C# 如何基于名称获取属性值,c#,asp.net,reflection,C#,Asp.net,Reflection,有没有办法根据对象的名称获取其属性的值 例如,如果我有: public class Car : Vehicle { public string Make { get; set; } } 及 我想写一个方法,在这里我可以传入属性名,它将返回属性值。即: public string GetPropertyValue(string propertyName) { return the value of the property; } 你必须使用反射 public object GetP
public class Car : Vehicle
{
public string Make { get; set; }
}
及
我想写一个方法,在这里我可以传入属性名,它将返回属性值。即:
public string GetPropertyValue(string propertyName)
{
return the value of the property;
}
你必须使用反射
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);
简单示例(无需在客户端编写反射硬代码)
另外,其他人回答说,使用扩展方法很容易获得任何对象的属性值,如:
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;
}
public static TResult GetPropertyValue(此对象为t,字符串为propertyName)
{
object val=t.GetType().GetProperties().Single(pi=>pi.Name==propertyName).GetValue(t,null);
返回(TResult)val;
}
如果愿意,您也可以对此进行一些错误处理。为了避免反射,您可以设置一个字典,在字典值部分中使用属性名作为键和函数,从您请求的属性返回相应的值 你想要的是GetValue而不是SetValue我可以对SetValue也这样做吗?如何设置?次要的事情-扩展方法可能不需要名为
car
的变量来查看如何基于propertyName字符串设置属性值,请参见此处的答案:请记住,由于它使用反射,因此速度要慢得多。可能不是问题,但需要注意。“无法从字符串转换为BindingFlags”是否有“更快”的方法@MattGreer?+1这是最好的答案,因为您正在显示所有中间对象,而不是传递属性值。我是否可以传递索引并获取属性名称和值(这样我就可以遍历所有属性)?@singhswat你应该把这当作一个新问题来问。从C#6开始,你可以使用null传播返回T.GetType().GetProperty(PropName)?.GetValue(T,null)代码>
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");
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;
}