无法将匿名方法转换为类型'System.Delegate',因为它不是委托类型

kat*_*tit 10 c# wpf

我想在WPF应用程序的主线程上执行此代码并获取错误我无法弄清楚出了什么问题:

private void AddLog(string logItem)
        {

            this.Dispatcher.BeginInvoke(
                delegate()
                    {
                        this.Log.Add(new KeyValuePair<string, string>(DateTime.Now.ToLongTimeString(), logItem));

                    });
        }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 22

匿名函数(lambda表达式和匿名方法)必须转换为特定的委托类型,而Dispatcher.BeginInvoke只需要Delegate.这有两种选择......

  1. 仍然使用现有BeginInvoke调用,但指定委托类型.这里有各种方法,但我通常将匿名函数提取到前一个语句:

    Action action = delegate() { 
         this.Log.Add(...);
    };
    Dispatcher.BeginInvoke(action);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 编写一个扩展方法,DispatcherAction不是Delegate:

    public static void BeginInvokeAction(this Dispatcher dispatcher,
                                         Action action) 
    {
        Dispatcher.BeginInvoke(action);
    }
    
    Run Code Online (Sandbox Code Playgroud)

    然后,您可以使用隐式转换调用扩展方法

    this.Dispatcher.BeginInvokeAction(
            delegate()
            {
                this.Log.Add(...);
            });
    
    Run Code Online (Sandbox Code Playgroud)

我也鼓励你使用lambda表达式而不是匿名方法,一般情况下:

Dispatcher.BeginInvokeAction(() => this.Log.Add(...));
Run Code Online (Sandbox Code Playgroud)

编辑:正如评论中所述,Dispatcher.BeginInvoke在.NET 4.5中获得了Action直接占用的重载,所以在这种情况下你不需要扩展方法.