gpt4 book ai didi

c# - 为什么 typeof(Child<>).BaseType.IsGenericTypeDefinition 是假的?

转载 作者:太空狗 更新时间:2023-10-29 21:48:34 26 4
gpt4 key购买 nike

例子:

class Base<T>{}
class Child<T> : Base<T>{}

typeof( Base<> ).IsGenericTypeDefinition; // == true ie. parameterless
typeof( Child<> ).BaseType.IsGenericTypeDefinition; // == false wtf???

// Eventually
typeof( Base<> ) != typeof( Child<> ).BaseType;

由于此功能 typeof( Child<> ).IsSubclassOf( typeof( Base<> ) )不管用。

最佳答案

我已阅读文档 here它解释了 IsGenericType 之间的区别和 IsGenericTypeDefinition .

你的 BaseType属于这一类:开放构造类型

The ContainsGenericParameters property is true.

Examples are a generic type that has unassigned type parameters, a type that is nested in a generic type definition or in an open constructed type, or a generic type that has a type argument for which the ContainsGenericParameters property is true.

It is not possible to create an instance of an open constructed type.

因此,为了使类型定义具有通用性,您必须能够从中创建实例。但在这种情况下,BaseType是一个开放的构造类型,它绑定(bind)到它的继承者:Child<T> , 如果你创建一个 Child<int>然后基地变成Base<int> ,反之亦然。

因此您不能直接从 BaseType 创建泛型类型实例调用MakeGenericType因为它的类型参数是在继承类 Child<T> 中声明的.

关于c# - 为什么 typeof(Child<>).BaseType.IsGenericTypeDefinition 是假的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51694379/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com