我遇到了泛型的奇怪行为。以下是我用于测试的代码。通用奇怪的行为
public static class Program
{
public static void Main()
{
Type listClassType = typeof(List<int>).GetGenericTypeDefinition();
Type listInterfaceType = listClassType.GetInterfaces()[0];
Console.WriteLine(listClassType.GetGenericArguments()[0].DeclaringType);
Console.WriteLine(listInterfaceType.GetGenericArguments()[0].DeclaringType);
}
}
输出:
System.Collections.Generic.List`1[T]
System.Collections.Generic.List`1[T]
我就觉得很奇怪的是,第二个Console.WriteLine调用显示类,而不是一个接口,因为我用一个泛型类型定义。这是正确的行为?
我想在我的编译器中实现泛型类型推断。假设我有下面的代码。
public static class GenericClass
{
public static void GenericMethod<TMethodParam>(IList<TMethodParam> list) { }
}
而且我想调用此方法如下:
GenericClass.GenericMethod(new List<int>());
为了检查推断的可能性,我得比较传递的参数在方法签名的类型,和类型。但是下面的代码返回false。
typeof(GenericClass).GetMethods()[0].GetParameters()[0].ParameterType == listInterfaceType;
我应该总是使用Type.GetGenericTypeDefinition进行这样的比较吗?
那么,在每一种情况下,你是从绑定的泛型列表采购的调用链,所以声明类型将永远是未绑定的泛型类型。你想做什么? –
JerKimball
2013-03-26 16:49:33