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

我为class1定义了一个依赖属性,它引发了一个事件。 我不知道为什么它给我这个错误“无法将lambda表达式转换为’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()方法仅将基类Delegate作为其参数。 但是这个类没有固有的签名,编译器需要这个签名才能自动将lambda表达式转换为适当的匿名方法并匹配委托实例。

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

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

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

请参阅相关讨论,例如, 为什么必须在作为普通的Delegate参数提供时转换lambda表达式 (如果您搜索Stack Overflow以查看您看到的错误消息,您将找到一些相关问题)。