Ответ 1
return car.GetType().GetProperty(propertyName).GetValue(car, null);
Есть ли способ получить значение свойства объекта на основе его имени?
Например, если у меня есть:
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;
}
return car.GetType().GetProperty(propertyName).GetValue(car, null);
Вам нужно будет использовать отражение
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");
Вы хотите Reflection
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");