是不是可以从通用列表中分配的通用IList?

rip*_*234 2 .net c# generics collections

bool IsTypeAGenericList(Type listType)
{
  typeof(IList<>).IsAssignableFrom(listType.GetGenericTypeDefinition())
}
Run Code Online (Sandbox Code Playgroud)

给定时返回false typeof(List<int>).

我假设这是因为两个类型参数可以不同,对吗?

rip*_*234 8

实际上,这有效:

public static bool IsGenericList(Type type)
{
  if (!type.IsGenericType)
    return false;
  var genericArguments = type.GetGenericArguments();
  if (genericArguments.Length != 1)
    return false;

  var listType = typeof (IList<>).MakeGenericType(genericArguments);
  return listType.IsAssignableFrom(type);
}
Run Code Online (Sandbox Code Playgroud)