I would like to be able to retrieve the name of a property of a type using a strongly typed syntax. I already got a function to get a property name of an instance:
public static string PropertyName<T, TReturn>(this T obj, Expression<Func<T, TReturn>> property) where T : class
{
MemberExpression body = (MemberExpression) property.Body;
if (body == null) throw new ArgumentException("The provided expression did not point to a property.");
return body.Member.Name;
}
Which can be called like this:
Car car = new Car();
car.PropertyName(x => x.Wheels) //returns "Wheels"
I'm trying to create another function that could support the following:
Type t = Typeof(Car);
t.PropertyName(x => x.Wheels) //should return "Wheels"
Or just (even better!):
Car.PropertyName(x => x.Wheels)
How would I go about this?
Aucun commentaire:
Enregistrer un commentaire