【发布时间】:2023-03-25 00:29:01
【问题描述】:
实例属性Type.IsConstructedGenericType 的文档不明确或具有误导性。
我尝试了以下代码来查找此属性和相关属性的实际行为:
// 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 种类型(除了 Dictionary<int, int>、Dictionary<int, string>、Dictionary<string, int>、Dictionary<string, string> 的 4 种组合之外的所有类型),ContainsGenericParameters 的值为 true。
对于 35 种类型,IsGenericTypeDefinition 为假,而IsConstructedGenericType 为真。对于最后一种类型,即(不出所料):
System.Collections.Generic.Dictionary`2[TKey,TValue]
IsGenericTypeDefinition 为真,IsConstructedGenericType 为假。
我能否得出结论,对于泛型类型,IsConstructedGenericType 的值始终是 IsGenericTypeDefinition 的相反值(否定)?
(文档似乎声称IsConstructedGenericType 与ContainsGenericParameters 相反,但我们清楚地展示了很多反例。)
【问题讨论】:
标签: c# .net generics reflection types