que suponer que usted no sólo quiere saber si el tipo es genérico, pero si un objeto es una instancia de un tipo genérico en particular, sin conocer los argumentos de tipo.
No es terriblemente simple, desafortunadamente. No es tan malo si el tipo genérico es una clase (como lo es en este caso), pero es más difícil para las interfaces. Aquí está el código para una clase:
using System;
using System.Collections.Generic;
using System.Reflection;
class Test
{
static bool IsInstanceOfGenericType(Type genericType, object instance)
{
Type type = instance.GetType();
while (type != null)
{
if (type.IsGenericType &&
type.GetGenericTypeDefinition() == genericType)
{
return true;
}
type = type.BaseType;
}
return false;
}
static void Main(string[] args)
{
// True
Console.WriteLine(IsInstanceOfGenericType(typeof(List<>),
new List<string>()));
// False
Console.WriteLine(IsInstanceOfGenericType(typeof(List<>),
new string[0]));
// True
Console.WriteLine(IsInstanceOfGenericType(typeof(List<>),
new SubList()));
// True
Console.WriteLine(IsInstanceOfGenericType(typeof(List<>),
new SubList<int>()));
}
class SubList : List<string>
{
}
class SubList<T> : List<T>
{
}
}
EDIT: Como se señaló en los comentarios, esto puede funcionar para interfaces:
foreach (var i in type.GetInterfaces())
{
if (i.IsGenericType && i.GetGenericTypeDefinition() == genericType)
{
return true;
}
}
Tengo la sospecha de que puede haber algunos casos extremos difíciles de todo esto, pero No puedo encontrar uno por el que falla por ahora.
Sin embargo, eso no detectará los subtipos. Ver mi respuesta También es mucho más difícil para las interfaces :( –