gpt4 book ai didi

c# - 如何在不实例化它们的情况下测试两个泛型是否具有基子类关系?

转载 作者:太空狗 更新时间:2023-10-29 23:10:45 25 4
gpt4 key购买 nike

我有以下通用类:

class Base<T> where T : ... { ... }
class Derived<T> : Base<T> where T : ... { ... }
class Another<T> where T : ... { ... }
class DerivedFromDerived<T> : Derived<T> where T : ... { ... }

在我的代码中的某处,我想测试给定的泛型是否继承自 Base<T> ,而不创建泛型的特定实例。我该怎么做?

static bool DerivedFromBase(Type type) { /* ??? */ }

static void Main(string[] args)
{
Console.WriteLine(DerivedFromBase(typeof(Derived<>))); // true
Console.WriteLine(DerivedFromBase(typeof(Another<>))); // false
Console.WriteLine(DerivedFromBase(typeof(DerivedFromDerived<>))); // true
Console.ReadKey(true);
}

编辑:谢谢马克。现在我看到了曙光。我最初尝试了以下方法:

typeof(Derived<>).BaseType == typeof(Base<>)

显然,这是正确的。 但事实并非如此。问题是Base的 T 与 Derived 不同的 T. 所以,在

typeof(Base<>)

BaseT是自由类型。但是,在

typeof(Derived<>).BaseType

BaseT绑定(bind)到 DerivedT ,这又是一种自由类型。 (这太棒了,我喜欢看到 System.Reflection 的源代码!)现在,

typeof(Derived<>).BaseType.GetGenericTypeDefinition()

无界BaseT .结论:

typeof(Derived<>).BaseType.GetGenericTypeDefinition() == typeof(Base<>)

现在,请原谅我,我的头在燃烧。

最佳答案

不确定这是否是您要查找的内容,但我认为“IsAssignableFrom”可以解决问题。

class Program
{
class Base<T> { }
class Derived<T> : Base<T> { }
class Another<T> { }
class DerivedFromDerived<T> : Derived<T> { }

static bool DerivedFromBase<T>(Type type)
{
return typeof(Base<T>).IsAssignableFrom(type);
}

static void Main(string[] args)
{
Console.WriteLine(DerivedFromBase<int>(typeof(Derived<int>))); // true
Console.WriteLine(DerivedFromBase<int>(typeof(Another<int>))); // false
Console.WriteLine(DerivedFromBase<int>(typeof(DerivedFromDerived<int>))); // true
Console.ReadKey(true);
}
}

处理开放基类型:

static bool DerivedFromBase(Type type)
{
Type openBase = typeof(Base<>);

var baseType = type;

while (baseType != typeof(Object) && baseType != null)
{
if (baseType.GetGenericTypeDefinition() == openBase) return true;

baseType = baseType.BaseType;
}
return false;
}

关于c# - 如何在不实例化它们的情况下测试两个泛型是否具有基子类关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5601486/

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