例如,假设我有一个方法将以下内容作为参数:
Expression<Func<T, object>> path
如何确定表达式中指定的“对象”的类型?更具体地说,我想确定它是否是集合类型(例如IEnumerable
)
答案 0 :(得分:2)
你已经在使用泛型,为什么不一直走?
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);
}
答案 1 :(得分:1)
或者,您可以执行以下操作(与通用类型参数更加一致):
// 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;
}
答案 2 :(得分:0)
Expression.Type
将回答这个问题(表达式的“结果”类型)。
要深入挖掘并且更普遍,您需要考虑不同的可能性,具体取决于Expression
实例的实际,运行时,类型 - 您实际拥有的subtypes of Expression
中的哪一个。