2011-12-21 123 views
2

我得到一個類型,其全名是:爲什麼我的測試「propType == typeof(ObservableCollection <string>)」失敗?

"System.Collections.ObjectModel.ObservableCollection`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]" 

的事情是,我想測試,如果我的類型爲字符串的一個ObservableCollection(在目前的情況下,)。因此,這裏是我的代碼:

if (propertyType.GetType() == typeof(ObservableCollection<string>)) 

但似乎失敗,我不明白爲什麼:/

我有這個代碼,這就是作品:

if (propertyType.Namespace == "System.Collections.ObjectModel" && propertyType.Name == "ObservableCollection`1") 
{ 
    //We are dealing with an ObservableCollection 
    var args = propertyType.GetGenericArguments(); 
    if (args.Count() != 0 && args[0] == typeof(string)) 
    { 
     //MyCode for ObservableCollection<string> 
    } 
} 

但我不覺得這是最佳的,並考慮到我將不得不處理其他類型的其他類型(int,bool,etcetc ...)的其他類型的集合(intn,bool,etcetc ...),這不太適合:(

+0

你能在你的問題中添加屬性聲明,以及如何填寫屬性類型變量?因爲它應該工作。 – Eilistraee 2011-12-21 09:32:28

+0

我正在做一個「typeof」的測試,所以我不需要在我的類型上使用「GetType()」:( – 2011-12-21 09:35:51

+0

你確定這就是你的所有代碼?這個Observable集合是一個類的peroprty嗎? – ChrisBD 2011-12-21 09:36:06

回答

8

在猜測,刪除多餘的.GetType()

if (propertyType == typeof(ObservableCollection<string>)) 

因爲propertyType.GetType()大概是System.Type(如System.RuntimeType)一些衍生物。

+0

From他的工作示例,這是最肯定的問題 – msarchet 2011-12-21 09:32:59

+0

噢,我的上帝,你是對的...... :(那個作品,我忘了我正在做一個測試「typeof」:( – 2011-12-21 09:33:35

+0

@GuillaumeSlashy有時你需要的只是新鮮的眼睛; p – 2011-12-21 09:35:03

0

使用:

if (propertyType is ObservableCollection<string>) 
{ } 
+0

propertyType將是'Type'類型;'Type'是**從來沒有**一個'ObservableCollection ';我會*期待*編譯器會發現這個並給出一個「總是虛假」的警告 – 2011-12-21 11:55:38

+0

哦,對不起,我以爲你在做propertyType.GetType()實際獲取類型並假定propertyType不是Type。 – 2011-12-21 13:50:15

相關問題