为什么我的测试“propType == typeof(ObservableCollection)”失败?
我得到一个类型,其全名是:
"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>
}
}
但我不觉得它是最佳的,并且考虑到我必须处理其他集合(IEnumerable,其他类型(int、bool、等等...)的列表等...)这不太适合:(
I got a Type whose FullName is :
"System.Collections.ObjectModel.ObservableCollection`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"
The thing is that I'd like to test if my Type is an ObservableCollection of string (in the current case, it is). So here is my code :
if (propertyType.GetType() == typeof(ObservableCollection<string>))
but it seems to fail and I don't understand why :/
I had this code thats works :
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>
}
}
but I don't feel like it's optimal and considering that I'll have to handle other collections (IEnumerable, List, etcetc...) of other Types (int, bool, etcetc...) this doesnt fit well :(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据猜测,删除额外的
.GetType()
:因为
propertyType.GetType()
可能是System.Type
的某种派生(例如System.RuntimeType
)。At a guess, remove the extra
.GetType()
:since
propertyType.GetType()
is probably some derivative ofSystem.Type
(such asSystem.RuntimeType
).使用:
use: