【问题标题】:Cannot convert lambda expression to type 'System.Delegate', Because it is not a delegate type无法将 lambda 表达式转换为类型“System.Delegate”,因为它不是委托类型
【发布时间】:2015-05-06 21:16:03
【问题描述】:

我为我的 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());
    }

}

【问题讨论】:

    标签: c# lambda dependency-properties


    【解决方案1】:

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

    也就是说,在您的代码示例中,您在属性 getter 中看到了您所询问的错误,因为编译器没有足够的信息来推断正确的委托类型。 Dispatcher.Invoke() 方法只是将基类Delegate 作为其参数。但是这个类没有固有的签名,编译器需要它来自动将 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 上搜索您看到的错误消息,您会发现一些相关问题)。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多