presumo che non si vuole solo sapere se il tipo è generico, ma se un oggetto è un'istanza di un particolare tipo generico, senza conoscere gli argomenti di tipo.
Non è terribilmente semplice, sfortunatamente. Non è male se il tipo generico è una classe (come in questo caso) ma è più difficile per le interfacce. Ecco il codice per una classe:
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: Come notato nei commenti, questo può funzionare per le interfacce:
foreach (var i in type.GetInterfaces())
{
if (i.IsGenericType && i.GetGenericTypeDefinition() == genericType)
{
return true;
}
}
ho un vago sospetto ci possono essere alcuni casi limite scomode intorno a questo, ma Non riesco a trovarne uno per il momento.
fonte
2009-06-11 17:38:07
Tuttavia, questo non rileva i sottotipi. Vedi la mia risposta. È anche molto più difficile per le interfacce :( –