我遇到了泛型的奇怪行爲。以下是我用於測試的代碼。通用奇怪的行爲
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