开发者

converting Linq/Lambda expressions to anonymous methods

开发者 https://www.devze.com 2023-03-15 06:04 出处:网络
I usually get code samples that uses lambda expressions. I am st开发者_开发知识库il using .net 2.0, and find it difficult to work with such code, for example

I usually get code samples that uses lambda expressions. I am st开发者_开发知识库il using .net 2.0, and find it difficult to work with such code, for example

foreach(var item in items)
{
    var catCopy = item;
    foreach(var word in words)
    {
        var wordCopy = word;
        var waitCallback = new WaitCallback(state =>
        {
            DoSomething(wordCopy, catCopy);
        });

        ThreadPool.QueueUserWorkItem(waitCallback);
    }
}

how do i convert such expression to any of its alternative(i.e non lambda code or anonymous methods)?

thanks


A lambda expression in C# is really just a delegate. Given your using .Net 2.0 you can use anonymous methods to define a delegate on the fly, so replace line of code with:

var waitCallback = new WaitCallback(
                        delegate(object state) { 
                             DoSomething(workCopy, catCopy); 
                        });


Why are you still using .Net 2? You're missing a lot of great changes, especially LINQ.

That being said, lambdas are not a feature of .Net 3.5, they are a feature of C# 3.0 and you can use that while compiling for .Net 2.0, if you really need to do that.

0

精彩评论

暂无评论...
验证码 换一张
取 消