问题
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
回答1:
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]);
回答2:
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:
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]);
}
来源:https://stackoverflow.com/questions/12898031/cannot-convert-anonymous-method-to-type-system-windows-threading-dispatcherprio