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.
精彩评论