检查Type或实例是否实现IEnumerable,而与Type T无关 [英] Checking if Type or instance implements IEnumerable regardless of Type T
问题描述
我在当前项目中进行了大量反思,并且尝试提供一些辅助方法以使所有内容保持整洁。
I'm doing a heavy bit of reflection in my current project, and I'm trying to provide a few helper methods just to keep everything tidy.
我希望提供一对方法来确定类型或实例是否实现 IEnumerable
–不管类型是 T
。这是我目前的状态:
I'd like to provide a pair of methods to determine if a type or instance implements IEnumerable
– regardless of the type T
. Here is what I have at the moment:
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
类型方法似乎根本不起作用–我曾期望直接 System.Collections.IEnumerable $ c使用
true
$ c>至少匹配。
The type method doesn't appear to work at all – I had expected a true
for the direct System.Collections.IEnumerable
match at least.
我知道 string
在技术上是可以枚举的,尽管有一些注意事项。但是,在这种情况下,理想情况下,我需要helper方法为其返回 false
。我只需要具有定义的 IEnumerable< T>
类型的实例即可返回 true
。
I'm aware that string
is technically enumerable, albeit with a few caveats. Ideally in this case, however, I'd need the helper method to return false
for it. I just need the instances with a defined IEnumerable<T>
type to return true
.
我可能只是错过了一些显而易见的东西–有人能指出我正确的方向吗?
I've probably just missed something fairly obvious – can anyone point me in the right direction?
推荐答案
以下行
return (type is IEnumerable);
询问是否类型
是 IEnumerable
,显然不是。
is asking "if an instance of Type
, type
is IEnumerable
", which clearly it is not.
您要执行的操作是:
return typeof(IEnumerable).IsAssignableFrom(type);
这篇关于检查Type或实例是否实现IEnumerable,而与Type T无关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!