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

C#使用MethodInfo获取类公共方法时如何正确排除事件相关方法

解决方案

C#编译器在编译event关键字定义的事件时,会自动为每个事件生成两个公共方法:add_事件名(处理订阅逻辑)和remove_事件名(处理退订逻辑),这两个方法会被GetMethods()正常返回,就是你现在不需要的多余条目。

正确的过滤逻辑不需要依赖字符串匹配,直接基于反射元数据判断即可:

  1. 先通过反射拿到目标类中所有事件对应的自动生成的add/remove方法
  2. 遍历方法时直接过滤掉这些方法即可,不会出现误判

修改后的代码如下:

public List<string> methodsList = new List<string>();

private void UpdateDropdownList()
{
    methodsList.Clear();
    Type targetType = typeof(WebcamScreenshootBehaviour);

    // 先拿到所有事件自动生成的add、remove方法,存入哈希集合用于快速判断
    var autoEventMethods = targetType.GetEvents()
        .SelectMany(e => new[] { e.AddMethod, e.RemoveMethod })
        .ToHashSet();

    // 如果还需要排除属性的get、set方法,可以取消注释下面这段
    // var autoPropertyMethods = targetType.GetProperties()
    //     .SelectMany(p => new[] { p.GetMethod, p.SetMethod })
    //     .ToHashSet();
    // autoEventMethods.UnionWith(autoPropertyMethods);

    MethodInfo[] methodInfos = targetType.GetMethods();
    foreach (var method in methodInfos)
    {
        if (method.DeclaringType == targetType 
            && method.IsPublic 
            && !autoEventMethods.Contains(method)) // 过滤自动生成的事件方法
        {
            methodsList.Add(method.Name);
        }
    }
}

该方案没有硬编码的字符串匹配逻辑,后续即使事件类型更换、或者你自己定义了add_开头的普通方法,也不会出现误判问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 09:42:02