Tim*_*uri 23
这将返回"True"
List<int> myList = new List<int>();
Console.Write(myList.GetType().IsGenericType && myList is IEnumerable);
Run Code Online (Sandbox Code Playgroud)
你是否想知道它是否恰好是一个"列表"......或者你是否可以使用IEnumerable和Generic?
以下方法将返回泛型集合类型的项类型.如果类型未实现ICollection <>则返回null.
static Type GetGenericCollectionItemType(Type type)
{
if (type.IsGenericType)
{
var args = type.GetGenericArguments();
if (args.Length == 1 &&
typeof(ICollection<>).MakeGenericType(args).IsAssignableFrom(type))
{
return args[0];
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
编辑:上述解决方案假定指定的类型具有自己的泛型参数.这对于使用硬编码通用参数实现ICollection <>的类型不起作用,例如:
class PersonCollection : List<Person> {}
Run Code Online (Sandbox Code Playgroud)
这是一个处理这种情况的新实现.
static Type GetGenericCollectionItemType(Type type)
{
return type.GetInterfaces()
.Where(face => face.IsGenericType &&
face.GetGenericTypeDefinition() == typeof(ICollection<>))
.Select(face => face.GetGenericArguments()[0])
.FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)