when should i use lambda expressions which comes w

2019-04-24 18:42发布

Hai guys,

My fellow developers were talking about lambda expressions this morning. So i decided to ask it here in SO

  • when should i use lambda expression which comes with C# 3.0?

标签: c# c#-3.0 lambda
4条回答
ら.Afraid
2楼-- · 2019-04-24 19:05

I don't think that there is a general rule when your should use them, but if I look to myself I tend to use them whenever I use anonymous methods. Most often this happens when spawning some code in a new thread using the ThreadPool, or when doing LINQ queries.

ThreadPool example:

ThreadPool.QueueUserWorkItem(state => {
    // the code to run on separate thread goes here
});

LINQ:

var myItems = GetSomeIEnumerable()
                  .Where(o => o.SomeProperty.Equals("some value"));
                  .OrderBy(o => o.SomeOtherProperty);
查看更多
Bombasti
3楼-- · 2019-04-24 19:08

Short answer: read "C# in depth" from SO's top-most voted fellow Jon Skeet. Its an excellent book and you will learn all about the new C# 3 features, especially when to use them, including Lambda expressions.

查看更多
Melony?
4楼-- · 2019-04-24 19:12

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

expect of using

del myDelegate = delegate(int x){return x*x; };
int j = myDelegate(5); //j = 25

you can write

del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
查看更多
甜甜的少女心
5楼-- · 2019-04-24 19:22

At least don't use for events á la

myUserControl.Loaded += (sender, e) => DoSomething(); // coding horror!!!1 :-P

because as of now you still can't unsubscribe and clean up things anymore then so easily. Sure there are WeakEventHandler factories and stuff out there but it's still best to remove all event handlers manually once the UserControl is removed from its parent.

For everything else, I think they do improve readability a lot, so use at own judgement.

查看更多
登录 后发表回答