Jep*_*sen 8 .net c# generics reflection types
实例属性的文档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);
}
}
Run Code Online (Sandbox Code Playgroud)
代码贯穿由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]
Run Code Online (Sandbox Code Playgroud)
这IsGenericTypeDefinition是真的,IsConstructedGenericType是假的.
我能否得出结论:对于泛型类型,值IsConstructedGenericType总是相反(否定)IsGenericTypeDefinition?
(该文件似乎声称IsConstructedGenericType相反ContainsGenericParameters,但我们清楚地展示了很多反例.)
是的,这是正确的.假设有Type问题的是通用类型,恰好是其中之一IsGenericTypeDefinition或是IsConstructedGenericType真的.我们可以很容易地从参考源的RuntimeType(这是具体落实的Type时候,你做你GetType()或typeof)为什么是这样的情况:
public override bool IsConstructedGenericType
{
get { return IsGenericType && !IsGenericTypeDefinition; }
}
Run Code Online (Sandbox Code Playgroud)