繁体   English   中英

为什么IsGenericTypeDefinition返回false?

[英]Why does IsGenericTypeDefinition return false?

我试图了解Type的IsGenericTypeDefinition属性。 据我了解,它只是没有任何替换类型的类模板(并且我们无法创建此类的实例)。 这是我的测试程序的代码:

class Test
{
    public class MyList<T> : List<T>
    {
    }
    public static void Main()
    {
    Console.WriteLine(typeof(MyList<>).GetMethod("Add").DeclaringType.IsGenericTypeDefinition);
    }
}

为什么程序打印false 我只是从泛型类型定义中获得此方法信息。 为什么没有通用的声明类型定义? 是虫子吗?

因为在这种情况下, DeclaringType是属于MyList<T>的通用类型参数TList<>的实例。

要获取未实例化的泛型类型,您需要使用GetGenericTypeDefinition ,它将返回List<>

typeof(MyList<>).GetMethod("Add").DeclaringType.GetGenericTypeDefinition() 

深入研究,我们得到:

var instantiationListArgs = typeof(MyList<>).GetMethod("Add").DeclaringType.GetGenericArguments();
var myListArg = typeof(MyList<>).GetGenericArguments();
var listArgs = typeof(List<>).GetGenericArguments();
Console.WriteLine(myListArg[0] == instantiationListArgs[0]); // Will output true, List was instantiated for the T in MyList
Console.WriteLine(listArgs[0] == instantiationListArgs[0]); // Will be false. The generic argument is different then the T in the free List<>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM