2016-01-13 17 views
1

如何確定ConstantExpression值爲null時的類型?我以前一直在使用下面的代碼檢測這個類型,但是當ConstantExpression Value爲null時它會導致一個空的異常。當Value爲null時從ConstantExpression獲取值類型

static Type GetType(Expression expression) 
{ 
    //causes exception when ((ConstantExpression)expression).Value is null 
    if (expression is ConstantExpression) 
     return ((ConstantExpression)expression).Value.GetType(); 

    //Check other types 
} 

想象一下,我表達的創建與此類似: -

int? value = null; 
ConstantExpression expression = Expression.Constant(value); 

而且我想,以確定int類型?

+1

'((常量表達式)表達)。 Type'? – Lee

+0

謝謝,那很簡單!如果你添加一個答案,我可以接受它。 – Joe

+0

供參考[正確的方法來檢查類型是否可爲空](http://stackoverflow.com/questions/8939939/correct-way-to-check-if-a-type-is-nullable) –

回答

1
expression.Type 

但請注意,如果您創建一個ConstantExpression與你在你的問題表明的工廠方法,其結果將是typeof(object),因爲當工廠檢查value它會得到一個空對象,而不是能請撥打GetType()就可以了。如果你要關心ConstantExpression的類型,即使是null,你也需要使用在類型參數中傳遞的重載。這也意味着,如果value一直沒null返回的類型將是typeof(int),不typeof(int?)

Expression.Constant((int?)null).Type // == typeof(object) 
Expression.Constant((int?)null, typeof(int?)).Type // == typeof(int?) 
Expression.Constant(null, typeof(int?)).Type // == typeof(int?) 
Expression.Constant((int?)3).Type // == typeof(int) 
Expression.Constant((int?)3).Value.GetType() // == typeof(int) 
Expression.Constant((int?)3, typeof(int?)).Type // == typeof(int?) 
Expression.Constant(3, typeof(int?)).Type // == typeof(int?) 

而最後,但並非最不重要:

Expression.Constant(null, typeof(int)) // ArgumentException thrown, "Argument types do not match" 
+0

感謝您的詳細解釋,非常有用 – Joe

相關問題