首页 > 解决方案 > MethodInfo 从找到的列表中获取事件

问题描述

我正在尝试将特定类的公共方法的所有名称添加到字符串列表中。

我说得很好,但由于某种原因,如果班级有一个事件,它也会被添加到列表中。

如何在不使用廉价技巧的情况下获得(System.Action)找到的字段的名称空间?

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

private void UpdateDropdownList()
{
    methodsList.Clear();

    MethodInfo[] methodInfos = typeof(WebcamScreenshootBehaviour).GetMethods();

    foreach (var method in methodInfos)
    {
        if (method.DeclaringType == typeof(WebcamScreenshootBehaviour) &&
            method.IsPublic &&
            method.ToString().Contains("System.Action") == false)   // Yuck!
        {
            methodsList.Add(method.Name);
        }
    }
}

这是 WebcamScreenshootBehaviour 类

 public class WebcamScreenshootBehaviour : MonoBehaviour
{
    public static event Action OnScreenshootIsTaken;
    public static event Action OnScreenshootIsReset;

    // Somewhere else in this class: OnScreenshootIsTaken?.Invoke();
}

截图

标签: c#unity3d

解决方案


我认为您还可以获取事件并将它们过滤掉,例如

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

private void UpdateDropdownList()
{
    var type = typeof(WebcamScreenshootBehaviour);

    var methodInfos = type.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly);
    var eventInfos = type.GetEvents(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly);

    methodsList = methodInfos 
                  // get only the names
                  .Select(method => method.Name)
                  // filter out if the name matches any of the event names
                  .Where(name => eventInfos.All(e => e.Name != name))
                  // then convert to list
                  .ToList();
}

如果这要少得多Yuck,我猜是有问题的;)


推荐阅读