gpt4 book ai didi

c# - 如何以编程方式订阅对象的所有事件?

转载 作者:太空狗 更新时间:2023-10-30 00:45:27 25 4
gpt4 key购买 nike

我正在尝试订阅由类似 WPF GridView 的第 3 方组件公开的 ALL 事件,以便进行一些调试。除了建议这可能不是调试它的最佳方式和类似的东西之外,我想知道这是否可以完成。

对于路由事件,它像这样工作正常:

var type = tree.GetType();
do
{
var staticFields = type.GetFields(BindingFlags.Static | BindingFlags.Public);
foreach (var staticField in staticFields)
{
if (typeof(RoutedEvent).IsAssignableFrom(staticField.FieldType))
{
tree.AddHandler((RoutedEvent)staticField.GetValue(null), new RoutedEventHandler(OnRoutedEvent), true);
}
}
} while ((type = type.BaseType) != typeof(object)/* && type.FullName.StartsWith("Telerik")*/);

public void OnRoutedEvent(object sender, System.Windows.RoutedEventArgs e)
{
Debug.WriteLine(e.RoutedEvent.ToString());
}

但是,对于典型的事件,这似乎不起作用:

var evts = tree.GetType().GetEvents();
foreach (var ev in evts)
{
ev.AddEventHandler(this, new EventHandler(OnEvent));
}

public void OnEvent(object sender, EventArgs e)
{
//..
}

因为它不喜欢委托(delegate)是 EventHandler 而不是专用类型,或者因为事件处理程序方法的签名不包含专用 EventArgs 类类型。

这能以某种方式完成吗?

------------ 稍后编辑--------在所有三种情况下(我的尝试、ds27680 的建议和 Thomas Levesque 的建议),AddEventHandler 调用都失败了:

        System.Reflection.TargetException occurred
Message=Object does not match target type.
Source=mscorlib
StackTrace:
at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.EventInfo.AddEventHandler(Object target, Delegate handler)
at Test.MainWindow..ctor() in c:\users\me\documents\visual studio 2010\Projects\Test\Test\MainWindow.xaml.cs:line 39

我想事件处理程序方法的签名与 EventArgs 类型不完全匹配是导致它失败的原因......

最佳答案

您需要将委托(delegate)“转换”为适当的类型:

var evts = tree.GetType().GetEvents();
EventHandler tmp = OnEvent;
foreach (var ev in evts)
{
Delegate handler = Delegate.CreateDelegate(ev.EventHandlerType, tmp.Target, tmp.Method);
ev.AddEventHandler(this, handler);
}

关于c# - 如何以编程方式订阅对象的所有事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5456726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com