简体   繁体   English

如何将该C#2委托示例转换为C#3 lambda语法?

[英]How can I convert this C# 2 delegate example to C# 3 lambda syntax?


I've got this example where I convert a C# 2 delegate example: 我有这个示例,其中我转换了一个C#2委托示例:

 Predicate<string> predicate2 = delegate(string n) { return n.StartsWith("J"); }; IList<string> namesWithJ2 = Tools.Filter(names, predicate2); Tools.Dump(namesWithJ2); 

to C# 3 lambda syntax example: C#3 lambda语法示例:

 var filteredNames = Tools.Filter(names, n => n.StartsWith("J")); Tools.Dump(filteredNames); 

But how to I convert this to lambda syntax? 但是,如何将其转换为lambda语法? Particularly, how do I get the two parameters (object s, DoWorkEventArgs args) to be passed using the "=>"? 特别是,如何获取要使用“ =>”传递的两个参数 (对象s,DoWorkEventArgs args)?

 _worker.DoWork += delegate(object s, DoWorkEventArgs args) { BackgroundWorker worker = s as BackgroundWorker; for (int i = 0; i < 10; i++) { if (worker.CancellationPending) { args.Cancel = true; return; } Thread.Sleep(1000); worker.ReportProgress(i + 1); } }; 
_worker.DoWork += (s, args) => {
    ....
};

Or if the compiler can't figure out the exact types of s and args: 或者,如果编译器无法确定s和args的确切类型:

_worker.DoWork += (object s, DoWorkEventArgs args) => {
    ....
};

The outline of the form is 表格的轮廓是

_worker.DoWork += (s, args) => {body of method};

Other punctuation as the compiler advises 编译器建议的其他标点符号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM