【问题标题】:How can I get the Type from a UnaryExpression?如何从 UnaryExpression 中获取类型?
【发布时间】:2015-10-14 11:17:45
【问题描述】:

我有一个属性定义为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? 的类型?

【问题讨论】:

    标签: c# reflection lambda expression-trees


    【解决方案1】:

    试试这个:

        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
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-11
      • 2011-09-03
      • 1970-01-01
      相关资源
      最近更新 更多