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

C#运行时初始化静态算法类列表实现动态调用方法及访问成员

方案实现说明

C# 中的静态类无法被实例化,不存在指向静态类实例的引用,你可以通过自定义包装结构提前把每个算法的元数据(Name、Alias)和 Execute 委托封装起来,所有反射操作都在初始化阶段完成,运行时零反射开销,性能完全满足高性能测试的需求。


具体实现步骤

  1. 定义算法信息包装类,用来统一存储每个算法的所有公共信息和执行委托:
public class AlgorithmInfo
{
    public string Name { get; set; }
    public string Alias { get; set; }
    public Func<int, int> Execute { get; set; }
}
  1. 在 algorithms 静态类中添加全局算法列表,用来存储初始化完成的所有算法入口:
public static List<AlgorithmInfo> AllAlgorithms { get; private set; } = new();
  1. 改写 initialize 方法,遍历算法类型时完成所有反射操作,封装后存入全局列表:
public static void initialize()
{
    var types = typeof(algorithms).GetNestedTypes(BindingFlags.Public | BindingFlags.Static).ToList();
    var algorithmList = new List<AlgorithmInfo>();

    foreach (Type t in types)
    {
        // 构造Execute方法委托
        var executeMethod = t.GetMethod("Execute");
        var executeDel = (Func<int, int>)Delegate.CreateDelegate(typeof(Func<int, int>), null, executeMethod);
        
        // 读取静态字段Name、Alias的值
        var name = t.GetField("Name", BindingFlags.Public | BindingFlags.Static)?.GetValue(null) as string;
        var alias = t.GetField("Alias", BindingFlags.Public | BindingFlags.Static)?.GetValue(null) as string;
        
        // 封装到统一结构
        algorithmList.Add(new AlgorithmInfo
        {
            Name = name,
            Alias = alias,
            Execute = executeDel
        });
    }

    AllAlgorithms = algorithmList;

    // 运行时使用示例,无任何反射开销
    foreach(var alg in AllAlgorithms)
    {
        int result = alg.Execute(0x12345678);
        Console.WriteLine($"算法{alg.Name}执行结果:{result}");
    }
}

补充说明

  • 如果你后续把 Name、Alias 改为常量,初始化阶段读取一次就足够,运行时不需要额外操作
  • 委托调用的性能和直接调用静态方法几乎无差异,完全符合最高性能测试的要求
  • 如果需要运行时修改静态类的 Name、Alias 并同步到包装类,可以把这两个字段也封装为读写委托,初始化阶段提前创建,运行时直接操作即可,无需反射

内容的提问来源于stack exchange,提问作者yo3hcv

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 13:24:00