c# - 检查 Type 或实例是否实现 IEnumerable 而不管类型 T

标签 c# .net inheritance reflection types

我正在对我当前的项目进行大量反射(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 的实例,typeIEnumerable”,显然不是。

你要做的是:

return typeof(IEnumerable).IsAssignableFrom(type);

关于c# - 检查 Type 或实例是否实现 IEnumerable 而不管类型 T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28701867/

相关文章:

c# - 流利的断言 : Should contain every element of sequence

c# - 最佳解决方案 : Extension Methods or a New Class?

c# - 无法使 CustomBinding 在 Mono 中工作

java继承找不到符号

c++ - 避免使用 Dynamic_Cast 的正确设计

c# - FakeItEasy - 新修改器的问题

c# - 如何替换 TreeView 中的 TreeNode?

c# - 定时器事件不触发按钮点击

c# - 如何将视频从网络摄像头流式传输到 IIS 媒体服务

Java:使用以父类作为类型参数的构造函数