2012-12-10 61 views
2

我想作類似於以下斷言:對象在C#表示某些類型

aMethod.ReturnType == double 
aString.GetType() == string 

上面的例子顯然不編譯,因爲doublestringType類型的對象,他們不是甚至是合法的C#表達式。

如何表示某個C#類型的Type

回答

6

使用typeof來獲取和比較類型。

aMethod.ReturnType == typeof(double) 

aString.GetType() == typeof(string) 
2

使用is操作者

檢查如果一個對象是與給定類型兼容。

bool result1 = aMethod.ReturnType是double;

bool result2 = aString is string; 

請看下面的例子:

bool result1 = "test" is string;//returns true; 
bool result2 = 2 is double; //returns false 
bool result3 = 2d is double; // returns true; 

編輯:我錯過了aMethod.ReturnType是一種沒有價值,所以你檢查它的更好的使用typeof

bool result1 = typeof(aMethod.ReturnType) == double; 

考慮下面的例子。

object d = 10d; 
bool result4 = d.GetType() == typeof(double);// returns true 
+0

'aMethod.ReturnType is double'這將返回false並給你一個編譯時間的警告,因爲'ReturnType'的類型是'Type',因此不可能是'double'。 –

+0

@NicolasRepiquet,謝謝你指出,我錯過了'ReturnType'是一個類型而不是一個值 – Habib

0

正如其他人說,使用typeof(YourType),或is操作(要小心,is是不是一個嚴格的運營商(想想繼承):例如,MyClass is object是真的)......

我不知道你爲什麼需要aMethod.ReturnType,但似乎你需要generic parameters。試一試 !