You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取C#泛型抽象基类Index<T>的所有派生类?

解决获取泛型抽象基类所有派生类的问题

我看你现在卡在没法正确获取Index<T>的所有派生类上,核心问题出在判断基类的逻辑上——直接用type.BaseType == indexBase是行不通的,因为Index<T>是开放泛型类型,而派生类的基类是构造后的封闭泛型类型(比如Index<SurveyChanged>),这俩根本不是同一个类型对象。

先理清楚你的代码结构:

泛型抽象基类

public abstract class Index<T> where T : class 
{ 
    public abstract string IndexName { get; } 
    public abstract string TypeName { get; } 
    public abstract Expression<Func<T, IConvertible>> IdFieldSelector { get; } 

    public string MakeSearchId(T item) 
    { 
        return ToSearchId(IdFieldSelector.Compile().Invoke(item)); 
    } 

    public string MakeSearchId(IConvertible idValue) 
    { 
        return ToSearchId(idValue); 
    } 

    private static string ToSearchId(IConvertible idValue) 
    { 
        return idValue.ToString(CultureInfo.InvariantCulture); 
    } 
}

派生类示例

public class SurveyChangedIndex : Index<SurveyChanged> 
{ 
    public override string IndexName => "reviews"; 
    public override string TypeName => "review"; 
    public override Expression<Func<SurveyChanged, IConvertible>> IdFieldSelector => sc => sc.SurveyResponseId; 
}

修正后的派生类获取代码

你需要调整类型筛选逻辑,判断派生类的基类是否是泛型类型,并且它的泛型定义等于原始的Index<>:

var indexBase = typeof(Index<>);
var assembly = Assembly.GetAssembly(indexBase);
var indexes = assembly.GetTypes()
    .Where(type => 
        type != indexBase && 
        !type.IsInterface && 
        !type.IsAbstract && 
        type.BaseType != null && 
        type.BaseType.IsGenericType && 
        type.BaseType.GetGenericTypeDefinition() == indexBase)
    .ToList();

关键逻辑解释

  • type.BaseType.IsGenericType:先确认派生类的基类是构造后的泛型类型
  • type.BaseType.GetGenericTypeDefinition():从构造后的泛型(比如Index<SurveyChanged>)中提取原始的开放泛型定义Index<>
  • 最后和indexBase(typeof(Index<>))做比较,这样就能精准匹配所有继承自任意Index<T>的派生类

额外注意事项:

  • 如果你的派生类分布在多个程序集里,Assembly.GetAssembly(indexBase)只能拿到基类所在程序集的类型,这时候需要遍历所有相关程序集来查找
  • 一定要加上type.BaseType != null的判断,避免空引用异常

内容的提问来源于stack exchange,提问作者Farhad-Taran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:11:28