在下面的代码中,通用逻辑的原因是因为,在我的应用程序中,我希望所有集合都是通用的。
bool IsCollectionType(Type type)
{
if (!type.GetGenericArguments().Any())
return false;
Type genericTypeDefinition = type.GetGenericTypeDefinition();
var collectionTypes = new[] { typeof(IEnumerable<>), typeof(ICollection<>), typeof(IList<>), typeof(List<>) };
return collectionTypes.Any(x => x.IsAssignableFrom(genericTypeDefinition));
}
我如何重构这段代码使其更智能或更简单?
bool IsEnumerableType(Type type)
{
return (type.GetInterface(nameof(IEnumerable)) != null);
}
或者如果您确实需要检查ICollection
:
bool IsCollectionType(Type type)
{
return (type.GetInterface(nameof(ICollection)) != null);
}
看“语法”部分:如果您需要排除字符串(本质上是 IEnumerable
),请使用以下函数:
bool IsEnumerableType(Type type)
{
return (type.Name != nameof(String)
&& type.GetInterface(nameof(IEnumerable)) != null);
}
DoesTypeSupportInterface(type, typeof(Collection<>))
public static bool DoesTypeSupportInterface(Type type,Type inter)
{
if(inter.IsAssignableFrom(type))
return true;
if(type.GetInterfaces().Any(i=>i. IsGenericType && i.GetGenericTypeDefinition()==inter))
return true;
return false;
}
或者您可以简单地检查非通用
IEnumerable
。所有的集合接口都继承自它。但我不会将任何实现
IEnumerable
的类型称为集合。
yourobject.GetType().GetInterfaces().Where(s => s.Name == "IEnumerable")
如果它有值,则为
IEnumerable
的实例。
ICollection
和
ICollection<T>
。
static bool IsCollectionType(Type type)
{
return type.GetInterfaces().Any(s => s.Namespace == "System.Collections.Generic" && (s.Name == "ICollection" || s.Name.StartsWith("ICollection`")));
}
private static bool IsCollectionType(Type type)
{
return type.GetInterfaces().Any(s => s.Namespace == "System.Collections.Generic" && (s.Name == "IEnumerable" || s.Name.StartsWith("IEnumerable`")));
}