C# 无法将匿名方法转换为类型';系统。代表';因为它不是委托类型

C# 无法将匿名方法转换为类型';系统。代表';因为它不是委托类型,c#,wpf,C#,Wpf,我想在WPF应用程序的主线程上执行此代码,但出现错误我无法找出错误: private void AddLog(string logItem) { this.Dispatcher.BeginInvoke( delegate() { this.Log.Add(new KeyValuePair<string, string>(Da

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

private void AddLog(string logItem)
        {

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

                    });
        }
private void AddLog(字符串登录项)
{
this.Dispatcher.BeginInvoke(
代表()
{
this.Log.Add(新的键值对(DateTime.Now.ToLongTimeString(),logItem));
});
}
匿名函数(lambda表达式和匿名方法)必须转换为特定的委托类型,而
Dispatcher.BeginInvoke
只接受
委托
。这有两种选择

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

    Action action = delegate() { 
         this.Log.Add(...);
    };
    Dispatcher.BeginInvoke(action);
    
  • Dispatcher
    上编写一个扩展方法,该方法采用
    操作
    而不是
    委托

    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中获得了一个重载,它直接执行
    操作,因此在这种情况下不需要扩展方法。

    您也可以使用:

    private void AddLog(string logItem)
            {
                this.Dispatcher.BeginInvoke((MethodInvoker) delegate
                {
                    this.Log.Add(new KeyValuePair<string, string>(DateTime.Now.ToLongTimeString(), logItem));
                });
            }
    
    private void AddLog(字符串登录项)
    {
    此.Dispatcher.BeginInvoke((MethodInvoker)委托
    {
    this.Log.Add(新的键值对(DateTime.Now.ToLongTimeString(),logItem));
    });
    }
    
    看看这里,我遇到了同样的问题,然后发现在.NET的4.5版本中,Dispatcher类得到了接受动作委托的重载(例如:),因此代码在没有明确委托类型规范的情况下工作。