Cannot convert anonymous method to type 'Syste

2019-07-19 08:45发布

Can anyone explain what I need to do to get past this error?

"Cannot convert anonymous method to type 'System.Windows.Threading.DispatcherPriority' because it is not a delegate type"

    private void Test(object sender)
    {
        base.Dispatcher.BeginInvoke(delegate
        {
                       //some code

        }, new object[0]);
    }

Thanks

3条回答
放荡不羁爱自由
2楼-- · 2019-07-19 09:10

EDIT
I got confused with you passing new object[0] as "parameter" to BeginInvoke and didn't realize that this actually means "no parameters", as everything following the delegate is in the params collection...

I'm making an example that expects a single integer.

You want to pass parameters, so it's best to use this

private void Test(object sender)
{
    base.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action<int>)delegate(int i)
    {
                   //some code

    }, 5);
}

This creates an anonymous delegate that takes an integer, converts this to an action that takes an integer and calls the delegate with the parameter 5.

查看更多
贪生不怕死
3楼-- · 2019-07-19 09:16

If you're using .NET 3.5 SP1 and upwards, then you can add a reference to System.Windows.Presentation.dll and make sure you have using System.Windows.Threading; at the top of the file. It contains extension methods that are easier to use, and allow you to simply write:

base.Dispatcher.BeginInvoke(() => { /* some code */ });

If you're using .NET 3.5 without SP1 or lower, then you'll have to cast the delegate to a concrete delegate type:

base.Dispatcher.BeginInvoke((Action) delegate { /* some code */ }, new object[0]);
查看更多
冷血范
4楼-- · 2019-07-19 09:21

Updated Answer

Cast the delegate to Action (or to Func<something> if you are returning a value).

private void Test(object sender)
{
    base.Dispatcher.BeginInvoke((Action)delegate
    {
        //some code
    }, new object[0]);
}

The first parameter of the Dispatcher.BeginInvoke method requires a System.Delegate. This is uncommon. Usually you would specify one of the Func or Action overloads. However, here it is possible to pass delegates with different signatures. Obviously anonymous delegates are not casted to System.Delegate implicitly.


UPDATE

I am working with .NET 3.5. In later Framework versions additional overloads of BeginInvoke may disturb C#'s overloading mechanism. Try

private void Test(object sender)
{
    base.Dispatcher.BeginInvoke((System.Delegate)(Action)delegate
    {
        //some code
    }, new object[0]);
}
查看更多
登录 后发表回答