c# - 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();
}
解决方案
我认为您还可以获取事件并将它们过滤掉,例如
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
,我猜是有问题的;)
推荐阅读
- javascript - 访问在动态导入的 JavaScript 中声明的变量?
- laravel - 使用 https://github.com/Maatwebsite/Laravel-Excel 调用成员函数 has() on null 时出错
- asp.net-core - 在 asp .net core 中写入一个 excel 文件
- amazon-web-services - 用户在注册时未收到确认码以及如何在 aws-amplify-react-native 中为此案例启用 MFA
- react-native - 错误命令失败:gradlew.bat app:installDebug
- python - 对熊猫中字符串的一部分进行分组
- kotlin - 使用文件模板生成 Kotlin 代码
- awk - 无法在此脚本中将文件复制到 linux 中的用户
- excel - 脚本任务在 Visual Studio 中工作,但在部署包时不工作
- python - 如何将进程名称和进程附加到字典?