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

时间:2009-07-30 09:06:33

标签: c# lambda

<小时/> 我有一个例子,我转换了 C#2 委托示例:

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

C#3 lambda语法示例:

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

但是如何将其转换为lambda语法?特别是,如何使用“=&gt;”传递两个参数(对象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);
    }
};

2 个答案:

答案 0 :(得分:1)

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

或者如果编译器无法确定s和args的确切类型:

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

答案 1 :(得分:1)

表格的大纲是

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

编译器建议的其他标点符号