【发布时间】:2016-04-08 06:25:25
【问题描述】:
System.Collections.Generic.IEnumerable'1[MyClass] 有问题
我的表达式返回null,但它不应该:
myCustomList.Where(x => x.bType != null && x.bType is IEnumerable<T>).FirstOrDefault();
我的 AddWatch 显示:
- 对于
T:System.Collections.Generic.List<MyClass> - 对于
x.bType:{System.Collections.Generic.IEnumerable'1[MyClass]}和dynamic {System.RuntimeType}作为Type -
x.bType is IEnumerable<T>返回false。 -
x.bType != null返回true。
x.bType 是一个属性,通常具有typeof(IEnumerable<MyClass>)) 的值。
更新
我把表情改成了...x.bType == typeof(IEnumerable<T>)..。
x.bType 显示为红色,{System.Collections.Generic.IEnumerable'1[MyClass]} 似乎无法将List<MyClass> 转换为IEnumerable<MyClass>?! ,因为我看到一个(如果我打开x.bType)System.InvalidOperationException 为x.bType.DeclaringMethod,x.bType.GenericParameterAttributes 和x.bType.GenericParameterPosition
我做错了什么?
解决方案:
感谢所有人,尤其是@Wilko van der Veen,这解决了我的问题:x.bType.IsAssignableFrom(typeof(T)),但也许有一个无需反思的解决方案,因为在我的情况下,relfection 并不是那么高效?!
【问题讨论】:
-
至少显示 bType 是如何设置的。
-
注意:
System.Collections.Generic.IEnumerable'1[MyClass]是一个字符串,是ToString()方法的结果,在IEnumerable<MyClass>类型上调用(调试器调用它来显示有关变量的信息)。所以真实的是System.Collections.Generic.IEnumerable<MyClass> -
@Henk Holterman
bType =typeof(IEnumerable<MyClass>)。感谢您的帮助 -
您必须创建一个minimal reproducible example。
-
更新了我的帖子,请再看一遍