【问题标题】:Why my test "propType == typeof(ObservableCollection<string>)" fails?为什么我的测试“propType == typeof(ObservableCollection<string>)”失败了?
【发布时间】:2011-12-21 09:27:00
【问题描述】:

我有一个全名是:

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

问题是我想测试我的 Type 是否是字符串的 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 等...)的其他集合(IEnumerable、List 等...),这不合适:(

【问题讨论】:

  • 您能否在问题中添加属性声明以及如何填充 propertyType 变量?因为它应该可以工作。
  • 我正在使用“typeof”进行测试,所以我不必在我的 Type 上使用“GetType()”:(
  • 你确定这就是你的全部代码吗?这个 Observable 集合是一个类的属性吗?

标签: c# generics observablecollection typeof


【解决方案1】:

猜测一下,去掉多余的.GetType()

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

因为propertyType.GetType() 可能是System.Type 的一些派生词(例如System.RuntimeType)。

【讨论】:

  • 哦,天哪,你是对的...... :( 那行得通我忘了我正在用“typeof”做测试:(
  • @GuillaumeSlashy 有时你需要的只是新鲜的眼睛;p
  • 哦。我怎么看不到这个。嗯..好的,不要在醒来后太早尝试去stackoverflow。
【解决方案2】:

使用:

if (propertyType is ObservableCollection<string>)
{ }

【讨论】:

  • propertyType 将是Type 类型; Type从不ObservableCollection&lt;string&gt;;我会期望编译器会发现这一点并给出“总是错误”的警告
  • 哦,对不起,我以为您正在执行 propertyType.GetType() 来实际获取类型并假定 propertyType 不是 Type。
猜你喜欢
  • 2014-08-14
  • 1970-01-01
  • 1970-01-01
  • 2016-10-05
  • 1970-01-01
  • 1970-01-01
  • 2014-11-22
  • 1970-01-01
  • 2021-02-09
相关资源
最近更新 更多