我们想要在Control.Invoke中匿名调用委托的语法有点麻烦.
我们已经尝试了许多不同的方法,但都无济于事.
例如:
myControl.Invoke(delegate() { MyMethod(this, new MyEventArgs(someParameter)); });
Run Code Online (Sandbox Code Playgroud)
其中someParameter是此方法的本地
以上将导致编译器错误:
无法将匿名方法转换为类型'System.Delegate',因为它不是委托类型
我希望我能恰当地提出问题的标题.
在c#中,我可以使用lambdas(作为委托),或者使用较旧的委托语法来执行此操作:
Func<string> fnHello = () => "hello";
Console.WriteLine(fnHello());
Func<string> fnHello2 = delegate()
{
return "hello 2";
};
Console.WriteLine(fnHello2());
Run Code Online (Sandbox Code Playgroud)
那么为什么我不能"内联"lambda或委托体,并避免在命名变量中捕获它(使其匿名)?
// Inline anonymous lambda not allowed
Console.WriteLine(
(() => "hello inline lambda")()
);
// Inline anonymous delegate not allowed
Console.WriteLine(
(delegate() { return "hello inline delegate"; })()
);
Run Code Online (Sandbox Code Playgroud)
在javascript中工作的示例(仅用于比较)是:
alert(
(function(){ return "hello inline anonymous function from javascript"; })()
);
Run Code Online (Sandbox Code Playgroud)
这会产生预期的警报框.
更新:看起来你可以在C#中使用内联匿名lambda,如果你适当地进行转换,但是()的数量开始让它变得难以驾驭.
// Inline anonymous lambda with appropriate cast IS allowed
Console.WriteLine(
((Func<string>)(() => "hello inline anonymous …Run Code Online (Sandbox Code Playgroud) 生成异常MessageBox.我怎样才能MessageBox在async方法中使用?
private async void Purchheard(object sender,EventArgs e)
{
Debug.WriteLine("??????? ???????");
try
{
await CurrentApp.RequestProductPurchaseAsync(ID,false);
if(license.ProductLicenses[ID].IsActive)
{
world.is_freemium=false;
}
}
catch (Exception ex)
{
MessageBox.Show("Finished!");
}
}
Run Code Online (Sandbox Code Playgroud)