不能将匿名方法转换为类型'因为它不是委托类型

本文关键字:类型 因为 方法 转换 不能 | 更新日期: 2023-09-27 18:08:37

我想在WPF应用程序的主线程上执行此代码并获得错误,我无法找出错误:

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

不能将匿名方法转换为类型'因为它不是委托类型

匿名函数(lambda表达式和匿名方法)必须转换为特定的委托类型,而Dispatcher.BeginInvoke只接受Delegate。这里有两个选项…

  1. 仍然使用已有的BeginInvoke呼叫,但指定委托类型。这里有多种方法,但我通常将匿名函数提取到前面的语句中:

    Action action = delegate() { 
         this.Log.Add(...);
    };
    Dispatcher.BeginInvoke(action);
    
  2. Dispatcher上写一个扩展方法,用Action代替Delegate:

    public static void BeginInvokeAction(this Dispatcher dispatcher,
                                         Action action) 
    {
        Dispatcher.BeginInvoke(action);
    }
    

    然后可以使用隐式转换

    调用扩展方法
    this.Dispatcher.BeginInvokeAction(
            delegate()
            {
                this.Log.Add(...);
            });
    

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

Dispatcher.BeginInvokeAction(() => this.Log.Add(...));

编辑:正如注释中所指出的,Dispatcher.BeginInvoke在。net 4.5中获得了重载,它直接接受Action,所以在这种情况下您不需要扩展方法。

你也可以使用MethodInvoker:

private void AddLog(string logItem)
        {
            this.Dispatcher.BeginInvoke((MethodInvoker) delegate
            {
                this.Log.Add(new KeyValuePair<string, string>(DateTime.Now.ToLongTimeString(), logItem));
            });
        }
相关文章: