2011-12-21 42 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