【问题标题】:Will IsConstructedGenericType always be the negation of IsGenericTypeDefinition, for a generic type?对于泛型类型,IsConstructedGenericType 是否始终是 IsGenericTypeDefinition 的否定?
【发布时间】: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&lt;int, int&gt;Dictionary&lt;int, string&gt;Dictionary&lt;string, int&gt;Dictionary&lt;string, string&gt; 的 4 种组合之外的所有类型),ContainsGenericParameters 的值为 true。

对于 35 种类型,IsGenericTypeDefinition 为假,而IsConstructedGenericType 为真。对于最后一种类型,即(不出所料):

System.Collections.Generic.Dictionary`2[TKey,TValue]

IsGenericTypeDefinition 为真,IsConstructedGenericType 为假。

我能否得出结论,对于泛型类型,IsConstructedGenericType 的值始终是 IsGenericTypeDefinition 的相反值(否定)?

(文档似乎声称IsConstructedGenericTypeContainsGenericParameters 相反,但我们清楚地展示了很多反例。)

【问题讨论】:

    标签: c# .net generics reflection types


    【解决方案1】:

    是的,这是正确的。假设所讨论的 Type 是泛型类型,则 IsGenericTypeDefinitionIsConstructedGenericType 中的一个是正确的。我们可以很容易地从reference source 换成RuntimeType(这是你在做GetType()typeof 时得到的Type 的具体实现)为什么会这样:

    public override bool IsConstructedGenericType 
    {
        get { return IsGenericType && !IsGenericTypeDefinition; } 
    } 
    

    【讨论】:

    • @ChristopherKing 我不会否认反射 API 处理部分构造的类型非常糟糕。
    猜你喜欢
    • 2010-09-10
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    • 2010-11-02
    相关资源
    最近更新 更多