【发布时间】:2015-04-26 10:25:30
【问题描述】:
我正在对我当前的项目进行大量反思,并且我正在尝试提供一些帮助方法来保持一切整洁。
我想提供一对方法来确定一个类型或实例是否实现了IEnumerable——不管T是什么类型。这是我目前拥有的:
public static bool IsEnumerable(this Type type)
{
return (type is IEnumerable);
}
public static bool IsEnumerable(this object obj)
{
return (obj as IEnumerable != null);
}
当我使用测试它们时
Debug.WriteLine("Type IEnumerable: " + typeof(IEnumerable).IsEnumerable());
Debug.WriteLine("Type IEnumerable<>: " + typeof(IEnumerable<string>).IsEnumerable());
Debug.WriteLine("Type List: " + typeof(List<string>).IsEnumerable());
Debug.WriteLine("Type string: " + typeof(string).IsEnumerable());
Debug.WriteLine("Type DateTime: " + typeof(DateTime).IsEnumerable());
Debug.WriteLine("Instance List: " + new List<string>().IsEnumerable());
Debug.WriteLine("Instance string: " + "".IsEnumerable());
Debug.WriteLine("Instance DateTime: " + new DateTime().IsEnumerable());
结果如下:
Type IEnumerable: False
Type IEnumerable<>: False
Type List: False
Type string: False
Type DateTime: False
Instance List: True
Instance string: True
Instance DateTime: False
type 方法似乎根本不起作用——我预计至少直接匹配 System.Collections.IEnumerable 的 true。
我知道string 在技术上是可枚举的,尽管有一些注意事项。但是,在这种情况下,理想情况下,我需要帮助器方法为其返回false。我只需要定义了IEnumerable<T> 类型的实例返回true。
我可能只是错过了一些相当明显的事情——谁能指出我正确的方向?
【问题讨论】:
-
我不明白这个问题。很清楚为什么
typeof()任何类型都不会返回true;您是在问 type object 是否实现了接口,而不是类型本身。也许你想要IsAssignableFrom()?但是您认为string的哪些方面不符合条件?它确实有“定义的IEnumerable<T>类型”。 -
是的,这就是类型一的问题——我整天都在研究类型和实例之间的反射嵌套,并且有点困惑!
string确实符合条件,但是在这种情况下,我确实需要排除它 - 在这个阶段可能更多的是方法命名问题。我想我会保持原样,然后添加另一个只对字符串进行检查的命令。 -
同意@JeroenMostert ...“重复”是在询问一个类型是否正在使用反射实现
IEnumerable<x>,这个是在询问一个类型是否正在实现IEnumerable,这是另一回事并且需要不同的解决方案(由不同的接受答案证明) -
也许你寻找的是
ICollection<x>而不是IEnumerable<x>
标签: c# .net inheritance reflection types