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

∥☆過路亽.° 提交于 2019-12-08 09:39:18

问题


I define a dependency Property for my class1, which raise an event. I don't know why it give me this error "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); }));
        }
    }

Very simple Class1 code :

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


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

}

回答1:


IMHO, it is generally better to address cross-thread needs outside of individual properties. The properties themselves should be simple, just calling GetValue() and SetValue(). In other words, a property getter or setter should not need to call Dispatcher.Invoke() at all.

That said, in your code example, you are seeing the error you're asking about in the property getter, because the compiler does not have enough information to infer the correct delegate type. The Dispatcher.Invoke() method simply takes as its parameter the base class Delegate. But this class has no inherent signature, which the compiler would need in order to automatically translate the lambda expression to an appropriate anonymous method and matching delegate instance.

Note that there is not a similar error in the setter. This is because you have provided the delegate type explicitly, through the use of the Action type's constructor. If you change the getter code to look more like the setter, it will work.

There are a few different syntaxes you could choose from, but this seems closest to the syntax you seem to prefer, based on the setter:

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


See related discussion at e.g. Why must a lambda expression be cast when supplied as a plain Delegate parameter (if you search Stack Overflow for the error message you're seeing, you'll find a few related questions).



来源:https://stackoverflow.com/questions/30087682/cannot-convert-lambda-expression-to-type-system-delegate-because-it-is-not-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!