我正在对我当前的项目进行大量反射(reflection),我正在尝试提供一些辅助方法以保持一切整洁。
我想提供一对方法来确定类型或实例是否实现了 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 方法似乎根本不起作用——我曾期待一个 true
对于直接System.Collections.IEnumerable
至少匹配。
我知道 string
在技术上是可枚举的,尽管有一些警告。然而,在这种情况下,理想情况下,我需要辅助方法来返回 false
为了它。我只需要定义了 IEnumerable<T>
的实例输入返回 true
.
我可能只是错过了一些相当明显的东西 - 谁能指出我正确的方向?
最佳答案
下一行
return (type is IEnumerable);
询问“如果 Type
的实例,type
是 IEnumerable
”,显然不是。
你要做的是:
return typeof(IEnumerable).IsAssignableFrom(type);
关于c# - 检查 Type 或实例是否实现 IEnumerable 而不管类型 T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28701867/