2016-08-14 74 views
1

我想設置一個數據類型,而不必在C#中創建額外的變量。而不是創建一個空變量,然後比較一個類型。使用字符串或其他格式比較數據類型

CustomType empty; //empty variable 
CustomType RealFooBar = new CustomType("extremeFoobar", false) //custom datatype with data in it 

if(RealFooBar.GetType() == empty.GetType()) 
    //operation 

我寧願做這樣的:

CustomType RealFooBar // already has data 

if(RealFooBar.GetType() == {CustomType}) 
    //operation 

有沒有辦法做到這一點?我試過typeof(CustomType)一次,但它似乎沒有這樣工作。或者我沒有做對。

+0

你的「意思似乎沒有工作「?假設你的代碼沒有錯誤,像'o.GetType()== typeof(Foo)'這樣的東西應該給你正確的結果。 –

+0

現在我感到很蠢。無論出於何種原因,它都有效... – Robokitty

回答

2

如果您事先知道類型,並且僅在您不知道的情況下使用GetType,則應該使用typeof,並且在運行時它會改變。

另一件事,如果你只需要你比較能is關鍵詞,參考文獻: IS keyword

任何這些應該工作:

if(RealFooBar is string) 
if(RealFooBar.GetType() == typeof(string)) 
相關問題