2012-01-07 45 views
1

當使用該類型的全名:System.Collections.ObjectModel.ObservableCollection<string>我似乎無法得到GetType().FullName工作,在那裏,如果我用一個List<string>它工作得很好,所以我有點困惑。System.Collections.ObjectModel.ObservableCollection <string>全名和Type.GetType失敗

下面的代碼失敗,我不明白爲什麼,因爲它工作正常,如果我用一個List<string>

System.Collections.ObjectModel.ObservableCollection<string> objectToTest = new System.Collections.ObjectModel.ObservableCollection<string>(); 
string typeFullName = objectToTest.GetType().FullName; 
Type typeBack = Type.GetType(typeFullName); 

if (typeBack == null) 
    throw new Exception(string.Format("Could not get type from: {0}", typeFullName)); 
+0

而你得到了什麼異常? – KMan 2012-01-07 12:25:21

+0

我得到錯誤''無法獲取類型:System.Collections.ObjectModel.ObservableCollection'1 [[System.String,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]'' 但是正如@ Marc-Gravell所示:''AssemblyQualifiedName''起作用。 – Nisd 2012-01-07 18:48:19

回答

1

歸結到一點,該類型是在; Type.GetType(string)不檢查到處(如果沒有組件被暗示,它只檢查調用程序集以及一個或兩個核心系統組件)。如果您使用.AssemblyQualifiedName而不是.FullName,它將工作(因爲生成的字符串有其他提示,允許Type.GetType(string)先解析正確的程序集)。

1

你要調用Type.GetType在AssemblyQualifiedName而不是FullName因爲後者不採取大會考慮