我有一个定义为Expression<Func<Kitten, object>>
的属性c => c.KittenAge
,其中KittenAge
是int?
我想得到这个类型。
我的代码是:
Expression<Func<Kitten, object>> property = c => c.KittenAge;
var unaryExpression = property.Body as UnaryExpression;
if (Nullable.GetUnderlyingType(unaryExpression.Type) == null)
{
// Error, must be nullable
}
不幸的是,由于Type
为System.Object
,因此始终会出现错误行。如何从表达式中获取int?
的类型?
答案 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
}