2015-10-14 34 views
0

我定義爲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?的類型?

回答

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 
    } 
+0

偉大的作品,謝謝。 – NibblyPig