简体   繁体   English

两种调用方法的方法有何区别?

[英]What is the difference between the two ways to invoke the method?

In the method below what is the difference between using 在下面的方法中,使用之间有什么区别

ListThreads.Add(new Task(() => item.Execute()));

and

ListThreads.Add(new Task(item.Execute));

private void Execute()
{
    for (int i = 0; i < ThreadNumber; i++)
    {
        ListObjects.Add(new MyClass(i + 1, ThreadNumber));
    }
    foreach (MyClass item in ListObjects)
    {
        ListThreads.Add(new Task(() => item.Execute()));
        ListThreads[ListThreads.Count - 1].Start();
    }
    Task.WaitAll(ListThreads.ToArray());
}

You ask the difference between 你问之间的区别

() => item.Execute()

and

item.Execute

The former is a lambda that calls item.Execute . 前者是调用item.Execute的lambda。 The, item.Execute , is a method group. item.Execute是一个方法组。 When they are passed to the constructor of Task they are both converted to a delegate of type Action . 当它们传递给Task的构造函数时,它们都将转换为Action类型的委托。

There is quite a difference though. 虽然有很大的不同。 The lambda captures the variable item . Lambda捕获可变item And the method group does not. 而方法组则没有。 This means that when the lambda is executed, the value of the variable item may be different from its value when you passed the lambda to the constructor of Task . 这意味着当执行lambda时,变量item的值可能与将lambda传递给Task的构造函数时的值不同。

To make the lambda version equivalent to the method group version you could introduce a local variable: 为了使lambda版本等同于方法组版本,您可以引入一个局部变量:

foreach (MyClass item in ListObjects)
{
    MyClass tmpItem = item;
    ListThreads.Add(new Task(() => tmpItem.Execute()));
    ListThreads[ListThreads.Count - 1].Start();
}

Do note that the language has been modified between C# 4.0 and C# 5.0. 请注意,该语言已在C#4.0和C#5.0之间进行了修改。 In C# 5.0 the code in your question behaves in exactly the same way as does the code above in this answer. 在C#5.0中,您问题中的代码的行为与此答案中以上代码的行为完全相同。 For more details see: 有关更多详细信息,请参见:

First of, it's a bad idea to use foreach variable in lambda expression. 首先,在lambda表达式中使用foreach变量是一个坏主意。 So, in this particular case the correct way is to write ListThreads.Add(new Task(item.Execute)); 因此,在这种情况下,正确的方法是编写ListThreads.Add(new Task(item.Execute));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM