gpt4 book ai didi

c# - 如何调用 Delegate.Target 的 .Invoke 方法?

转载 作者:太空宇宙 更新时间:2023-11-03 12:55:04 28 4
gpt4 key购买 nike

给定以下方法:

public static void ExecuteAsync( this EventHandler eH, object sender, EventArgs eA ) {
eH.GetInvocationList( ).Cast<EventHandler>( ).ToList( ).ForEach( e => {
e.BeginInvoke( sender, eA, IAR =>
( ( IAR as AsyncResult ).AsyncDelegate as EventHandler ).EndInvoke( IAR ), null );
} );
}

我注意到 e 有一个属性 Target。

当我进一步研究它时,我发现我可以检查 e.Target 是 System.Windows.Controls.Control 还是 e.Target 是 System.Windows.Forms.Control.

这太棒了,因为在使用这个扩展的情况下,为了方便(而且我很懒),我希望能够判断委托(delegate)目标是否需要调用委托(delegate)(在这种情况下WinForms:Control.Invoke(foo);对于 WPF:Control.Dispatcher.Invoke(foo)).

我不需要知道如何将对象转换为它的实际类型(我可以没有它):我只需要知道如何转换对象以便我可以访问 InvokeRequired 属性和 Invoke 方法(在 WinForms 控件的情况下),或 Dispatcher 属性(用于访问 Dispatcher.CheckAccess( ) 函数和 Dispatcher.Invoke( ) 方法)。

这可能吗?我该怎么做呢? (我试过将 e.Target 转换为 System.Windows.Control.Control 但结果没有 Dispatcher 属性)。

编辑

根据对转换代码(和导入/引用)的请求:

判断是否为WPF控件:

( if e.Target is System.Windows.Controls.Control ){ //Fully Qualified
( e.Target as System.Windows.Controls.Control)./*...*/;
}

判断是否为WinForms控件:

( if e.Target is System.Windows.Forms.Control ){ //Fully Qualified
( e.Target as System.Windows.Forms.Control )./*...*/;
}

该项目引用了几个库:

Microsoft.CSharp
MySql.Data
PresentationFramework
System
System.Configuration
System.Configuration.Install
System.Core
System.Data
System.Data.DataSetExtensions
System.Drawing
System.Management
System.Windows.Forms
System.Xml
System.Xml.Linq

最佳答案

这不适合你。这不是最优雅的方式,但可以检查目标是 WPF 还是 WinForms 控件:

if (e.Target is System.Windows.Controls.Control)
{
var wpfTarget = ((System.Windows.Controls.Control)e.Target);
if (wpfTarget.Dispatcher.CheckAccess()) // check if on dispatcher thread
{
wpfTarget.Dispatcher.Invoke(/*...*/);
}

}
else if (e.Target is System.Windows.Forms.Control)
{
var formsTarget = (System.Windows.Forms.Control)e.Target;
if (formsTarget.InvokeRequired)
{
formsTarget.Invoke(/*...*/);
}
}

在 VisualStudio 中,我对 wpfTarget 上的 Dispatcher 提供了 Intelisense 支持:

enter image description here

编辑

在我包含的引用文献下方

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

其中只有四个在使用:

using System;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Windows;

关于c# - 如何调用 Delegate.Target 的 .Invoke 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34192689/

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