Looping through a list of Actions

前端 未结 3 723
小鲜肉
小鲜肉 2020-12-11 03:12

I can\'t understand how to loop through an Action list. When I try it, I end up with the values being the same as the previous iteration.

Here\'s the co

3条回答
  •  感情败类
    2020-12-11 04:02

    This behaviour is conditionize by Closures.

    The variable that is present in your lambda is a reference and not value copy. That means that points to the latest value assumed by str, which is "ghi" in your case. That's why for every call it just goes to the same memory location and recovers, naturally, same value.

    If you write the code, like in answers provided, you force a C# compiler to regenerate a new value each time, so a new address will be passed to the labmda, so every lambda will have it's own variable.

    By the way, if I'm not mistake, C# team promise to fix this non natural behaviour in C# 5.0. So it's better to check their blog on this subject for future updates.

提交回复
热议问题