【发布时间】:2021-07-08 07:16:46
【问题描述】:
private List<EventInfo> GetAllTheEventsTheControlCanPublish(Control control)
{
return control.GetType().GetEvents().ToList();
}
问题是:如何仅获取控件已发布的事件列表? 我有一个简单的 winform 应用程序:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
namespace GettingAllEventsOfAControl
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
_listOfSelectableValues = new List<int>() { 3, 5, 8, 11, 15 };
foreach (int currentValue in _listOfSelectableValues)
{
comboBox1.Items.Add(currentValue);
}
comboBox1.SelectedIndexChanged += new EventHandler(comboBox1_SelectedIndexChanged);
comboBox1.Click += new EventHandler(comboBox1_Click);
_allTheEventsTheControlCanPublish = GetAllTheEventsTheControlCanPublish(comboBox1);
}
private List<int> _listOfSelectableValues;
private List<EventInfo> _allTheEventsTheControlCanPublish;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void comboBox1_Click(object sender, EventArgs e)
{
}
private List<EventInfo> GetAllTheEventsTheControlCanPublish(Control control)
{
return control.GetType().GetEvents().ToList();
}
}
}
我想要一个类似的方法:
private List<EventInfo> GetPublishedEvents(Control control)
{
return ...;
}
在这种情况下将返回一个包含 2 个项目的列表:
- SelectedIndex 已更改
- 点击
即使 dr.null 让步了,我的问题仍然有效:
给定一个控件,有没有办法获取仅包含该控件实际发布的事件的 EventInfo 类型的对象列表?
以不同的形式提出问题:
GetPublishedEvents(Control control) 方法返回特定控件可以发布的所有事件的 EventInfo 类型的对象列表。
如果相应的控件实际发布了此特定事件,是否有对象 EventInfo 的字段或属性的值发生更改?
然后,我可以遍历列表 allTheEventsTheControlCanPublish 中的所有对象并检查此字段或属性的值,从而找出实际发布了哪些事件。
【问题讨论】:
-
Some useful info here 以及为什么很难获得您想要的列表。你能解释一下你想做什么吗?也许还有其他方法。
-
在我删除控件之前,我必须取消它订阅的所有事件。 你确定吗?为什么?
-
@TaW 根据docs.microsoft.com/en-us/dotnet/desktop/winforms/controls/…:以编程方式从集合中删除控件 从事件中删除事件处理程序。在 Visual Basic 中,使用 RemoveHandler 语句关键字;在 C# 中,使用 -= 运算符。使用 Remove 方法从面板的 Controls 集合中删除所需的控件。调用Dispose方法释放控件使用的所有资源。
-
那么就
-=你+=你自己。就这么简单。 -
这不是一个答案,而是一个评论,只是为了在我回答之前看看你是否能理解并且你投反对票,因为也许你不明白。编译和运行完美。您可以使用 Visual Studio 的帮助来确定您需要的内容。如果需要,请说明您的 .NET 版本和 C# 编译器版本。
标签: c# visual-studio-2010 events