//ModelFor(person =>person.Name);
public void ModelFor<TModel, TValue>(
Expression<Func<TModel, TValue>> expression)
{
//Result should be "Name"
string nameOfTValue = ????;
}
EDIT: After your edit, I think you are want the name of the member involved in the expression, assuming of course that the expression is a member-expression in the first place.
((MemberExpression)expression.Body).Member.Name
To be more robust, you can do:
var memberEx = expression.Body as MemberExpression;
if (memberEx == null)
throw new ArgumentException("Body not a member-expression.");
string name = memberEx.Member.Name;
(Not relevant anymore):
To get a System.Type
that represents the type of the TValue
type-argument, you can use the typeof
operator.
You probably want:
typeof(TValue).Name
But also consider the FullName
and AssemblyQualifiedName
properties if appropriate.
This really has nothing to do with expression-trees; you can use this technique to get the type of a type-argument for any generic method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With