How do I find out the type specified by an Expression?
For example, let's say I have a method that takes th开发者_开发百科e following as a parameter:
Expression<Func<T, object>> path
How do I determine the type of the 'object' specified in the expression? More specifically, I'd like to determine if it's a collection type (eg. IEnumerable
)
You're already using generics, so why not go all the way?
void GetMemberType<TArg, TProperty>(Expression<Func<TArg, TProperty>> path)
{
// Get the member ...
var member = path.Body as MemberExpression;
// ... Do whatever you want with the member ...
// Now get the type
var memberType = typeof(TProperty);
}
Alternatively, you could do something like the following (which is more inline with you generic type arguments):
// Get your expression
// (probably already provided as an arg to one of your methods, I'm willing to bet)
Expression<Func<T, object>> path = ...
var memberExpr = path.Body as MemberExpression;
var member = memberExpr.Member;
Type type;
if (member is FieldInfo)
{
var field = member as FieldInfo;
type = field.FieldType;
}
if (member is PropertyInfo)
{
var property = member as PropertyInfo;
type = property.PropertyType;
}
Expression.Type
will answer this (the "result" type of the expression).
To dig deeper and more generally you will need to consider different possibilities depending on the actual, runtime, type of the Expression
instance—which of the many subtypes of Expression
do you actually have.
精彩评论