无法将 lambda 表达式转换为类型 'System.Delegate',因为它不是委托类型

Cannot convert lambda expression to type 'System.Delegate', Because it is not a delegate type

我为我的 class1 定义了一个依赖项 属性,它引发了一个事件。我不知道为什么会给我这个错误 "Cannot convert lambda expression to type 'System.Delegate'"

        public static readonly DependencyProperty class1Property =
        DependencyProperty.Register("class1Property", typeof(Class1), typeof(UserControl1), new PropertyMetadata(null));

    public Class1 class1
    {
        get
        {
            return Dispatcher.Invoke((() => GetValue(class1Property)))as Class1;
        }
        set
        {
            Dispatcher.Invoke(new Action(() => { SetValue(class1Property, value); }));
        }
    }

非常简单的 Class1 代码:

    public class Class1
{
    public delegate void myhandler(object sender, EventArgs e);
    public event myhandler test;


    public void connection()
    {
        test(this, new EventArgs());
    }

}

恕我直言,通常最好在单个属性之外解决跨线程需求。属性本身应该很简单,只需调用 GetValue()SetValue()。换句话说,属性 getter 或 setter 根本不需要调用 Dispatcher.Invoke()

就是说,在您的代码示例中,您在 属性 getter 中看到了您询问的错误,因为编译器没有足够的信息来推断正确的委托类型. Dispatcher.Invoke() 方法仅将基数 class Delegate 作为其参数。但是这个 class 没有固有的签名,编译器需要它来自动将 lambda 表达式转换为适当的匿名方法和匹配的委托实例。

注意 setter 中没有类似的错误。这是因为您通过使用 Action 类型的构造函数显式提供了委托类型。如果您将 getter 代码更改为看起来更像 setter,它将起作用。

您可以选择几种不同的语法,但这似乎最接近您喜欢的语法,基于 setter:

get
{
    return Dispatcher.Invoke(
        new Func<object>(() => GetValue(class1Property))) as Class1;
}


请参阅相关讨论,例如Why must a lambda expression be cast when supplied as a plain Delegate parameter(如果您在 Stack Overflow 中搜索您看到的错误消息,您会发现一些相关问题)。