如何从UnaryExpression中获取Type?

时间:2015-10-14 11:17:46

标签: c# reflection lambda expression-trees

我有一个定义为Expression<Func<Kitten, object>>的属性c => c.KittenAge,其中KittenAgeint?

我想得到这个类型。

我的代码是:

Expression<Func<Kitten, object>> property = c => c.KittenAge;

var unaryExpression = property.Body as UnaryExpression;

if (Nullable.GetUnderlyingType(unaryExpression.Type) == null)
{
   // Error, must be nullable
}

不幸的是,由于TypeSystem.Object,因此始终会出现错误行。如何从表达式中获取int?的类型?

1 个答案:

答案 0 :(得分:3)

试试这个:

    Expression<Func<Kitten, object>> property = c => c.KittenAge;
    var unaryExpression = property.Body as UnaryExpression;
    var propertyExpression = unaryExpression.Operand as MemberExpression;

    if (Nullable.GetUnderlyingType(propertyExpression.Type) == null)
    {
      // Error, must be nullable
    }