Cod*_*r 2 137 c# asp.net reflection
有没有办法根据对象的名称获取对象属性的值?
例如,如果我有:
public class Car : Vehicle
{
public string Make { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
和
var car = new Car { Make="Ford" };
Run Code Online (Sandbox Code Playgroud)
我想写一个方法,我可以传入属性名称,它将返回属性值.即:
public string GetPropertyValue(string propertyName)
{
return the value of the property;
}
Run Code Online (Sandbox Code Playgroud)
Mat*_*eer 288
return car.GetType().GetProperty(propertyName).GetValue(car, null);
Run Code Online (Sandbox Code Playgroud)
Ada*_*kis 42
你必须使用反射
public object GetPropertyValue(object car, string propertyName)
{
return car.GetType().GetProperties()
.Single(pi => pi.Name == propertyName)
.GetValue(car, null);
}
Run Code Online (Sandbox Code Playgroud)
如果你想要真正的幻想,你可以使它成为一个扩展方法:
public static object GetPropertyValue(this object car, string propertyName)
{
return car.GetType().GetProperties()
.Single(pi => pi.Name == propertyName)
.GetValue(car, null);
}
Run Code Online (Sandbox Code Playgroud)
然后:
string makeValue = (string)car.GetPropertyValue("Make");
Run Code Online (Sandbox Code Playgroud)
Chu*_*age 33
你想要反思
Type t = typeof(Car);
PropertyInfo prop = t.GetProperty("Make");
if(null != prop)
return prop.GetValue(this, null);
Run Code Online (Sandbox Code Playgroud)
另外其他人回答,它很容易通过使用扩展方法获取任何对象的属性值,例如:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
用法是:
Car foo = new Car();
var balbal = foo.GetPropertyValue("Make");
Run Code Online (Sandbox Code Playgroud)
简单示例(客户端没有写反射硬代码)
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"));
}
Run Code Online (Sandbox Code Playgroud)
扩展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;
}
Run Code Online (Sandbox Code Playgroud)
如果愿意,您也可以对此进行一些错误处理。