实例属性的文档Type.IsConstructedGenericType http://msdn.microsoft.com/en-us/library/system.type.isconstructedgenerictype.aspx不清楚或具有误导性。
我尝试使用以下代码来查找此属性和相关属性的实际行为:
// create list of types to use later in a Dictionary<,>
var li = new List<Type>();
// two concrete types:
li.Add(typeof(int));
li.Add(typeof(string));
// the two type parameters from Dictionary<,>
li.Add(typeof(Dictionary<,>).GetGenericArguments()[0]);
li.Add(typeof(Dictionary<,>).GetGenericArguments()[1]);
// two unrelated type parameters
li.Add(typeof(Func<,,,>).GetGenericArguments()[1]);
li.Add(typeof(EventHandler<>).GetGenericArguments()[0]);
// run through all possibilities
foreach (var first in li)
{
foreach (var second in li)
{
var t = typeof(Dictionary<,>).MakeGenericType(first, second);
Console.WriteLine(t);
Console.WriteLine(t.IsGenericTypeDefinition);
Console.WriteLine(t.IsConstructedGenericType);
Console.WriteLine(t.ContainsGenericParameters);
}
}
代码运行的是由36种类型组成的笛卡尔积t
.
结果:对于 32 种类型(除了 4 种组合之外的所有类型)Dictionary<int, int>
, Dictionary<int, string>
, Dictionary<string, int>
, Dictionary<string, string>
), 的价值ContainsGenericParameters
是真的。
对于 35 种类型,IsGenericTypeDefinition
是假的,而IsConstructedGenericType
是真的。对于最后一种类型,即(毫不奇怪):
System.Collections.Generic.Dictionary`2[TKey,TValue]
the IsGenericTypeDefinition
是真的并且IsConstructedGenericType
是假的。
我能否得出这样的结论:对于泛型类型,IsConstructedGenericType
总是相反(否定)IsGenericTypeDefinition
?
(该文件似乎声称IsConstructedGenericType
相反ContainsGenericParameters
,但我们显然展示了很多反例。)