要判断一个类是否继承于泛型基类,可以使用C#中的Type类和反射机制。
首先,使用Type类获取这个类的Type对象,然后使用Type对象的IsSubclassOf方法判断这个类是否继承于泛型基类。IsSubclassOf方法需要一个参数,即要判断的基类的Type对象。下面是一个示例代码:
using System;
class Program
{
static void Main()
{
Type derivedType = typeof(DerivedClass);
if (derivedType.IsSubclassOf(typeof(GenericBaseClass<>)))
{
Console.WriteLine("DerivedClass is derived from GenericBaseClass");
}
else
{
Console.WriteLine("DerivedClass is not derived from GenericBaseClass");
}
}
}
class GenericBaseClass<T>
{
}
class DerivedClass : GenericBaseClass<int>
{
}
输出结果是:DerivedClass is derived from GenericBaseClass
上述示例中,首先获取DerivedClass的Type对象,然后使用IsSubclassOf方法判断是否继承于GenericBaseClass<>,由于DerivedClass确实继承于GenericBaseClass
另外一个示例中,BaseClass派生出DerivedClass,而DerivedClass又派生出TwoDerivedClass,其中DerivedClass继承于GenericBaseClass
using System;
class Program
{
static void Main()
{
Type twoDerivedType = typeof(TwoDerivedClass);
if (twoDerivedType.IsSubclassOf(typeof(GenericBaseClass<>)))
{
Console.WriteLine("TwoDerivedClass is derived from GenericBaseClass");
}
else
{
Console.WriteLine("TwoDerivedClass is not derived from GenericBaseClass");
}
}
}
class GenericBaseClass<T>
{
}
class BaseClass
{
}
class DerivedClass : GenericBaseClass<int>
{
}
class TwoDerivedClass : DerivedClass
{
}
输出结果是:TwoDerivedClass is derived from GenericBaseClass。
上述示例中,Type对象twoDerivedType表示TwoDerivedClass,然后使用IsSubclassOf方法判断是否继承于GenericBaseClass<>,其实就是判断TwoDerivedClass是否继承于DerivedClass,以及DerivedClass是否继承于GenericBaseClass<>。
如果TwoDerivedClass继承了DerivedClass而DerivedClass继承了GenericBaseClass
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:c#中判断类是否继承于泛型基类 - Python技术站