当然你可以... List<>实际上是所谓的"未绑定泛型类型",这意味着它尚未使用类型进行参数化.当指定type参数时,它被称为"绑定泛型类型".涉及"原始"类型参数的类型,如List<T>"开放泛型类型",以及仅涉及实际类型的类型,如List<int>"封闭泛型类型".在C#中可以使用未绑定泛型类型的唯一情况是typeof运算符.要访问未绑定类型或封闭类型,您可以执行以下操作:
Type listOfT = typeof(List<>); // unbound type
Type listOfString = typeof(List<string>); // closed bound type
Type listOfInt32 = typeof(List<int>); // closed bound type
Assert.IsTrue(listOfString.IsGenericType);
Assert.AreEqual(typeof(string), listOfString.GetGenericTypeParameters()[0]);
Assert.AreEqual(typeof(List<>), listOfString.GetGenericTypeDefinition());
Type setOfString = typeof(HashSet<string>);
Assert.AreNotEqual(typeof(List<>), setOfString.GetGenericTypeDefinition());
Run Code Online (Sandbox Code Playgroud)
其实List<T> 是在许多方面实型(可以使用typeof(List<>),例如),和List<T>是不是只是一个编译器的伎俩,但运行时的把戏.但你确实可以检查开放的泛型类型,例如:
static Type GetRawType(Type type)
{
return type.IsGenericType ? type.GetGenericTypeDefinition() : type;
}
static void Main()
{
List<int> list1 = new List<int>();
List<string> list2 = new List<string>();
Type type1 = GetRawType(list1.GetType()),
type2 = GetRawType(list2.GetType());
Console.WriteLine(type1 == type2); // true
}
Run Code Online (Sandbox Code Playgroud)