猿问

如何从 C# 中的 lambda 表达式中删除列表项?

如果我有这个


private static List<Action> actions = new List<Action>();


private static void Main()

{

    for (var i = 0; i < 10; i += 1)

    {

        Action action = async () => {

            // want to remove this specific lambda item from the "actions" variable. 

            // is there something like this:

            /*

                Action this_action = this;

                actions.Remove(this_action);

            */

        };


        actions.Add(action);

    }


    Parallel.Invoke(actions.ToArray());


    Console.Write("\nPress any key to exit...");

    Console.ReadKey();

}

如何从列表中正确删除它。我需要某种自我参考?


DIEA
浏览 462回答 1
1回答

皈依舞

您可以仅使用 to 的引用action来删除操作的实例。关闭将确保引用指向正确的对象。for (var i = 0; i < 10; i += 1){&nbsp; &nbsp; Action action = null;&nbsp; &nbsp; action = () => {&nbsp; &nbsp; &nbsp; &nbsp; actions.Remove(action);&nbsp; &nbsp; };&nbsp; &nbsp; actions.Add(action);}Parallel.Invoke(actions.ToArray());有关工作示例,请参阅Fiddle。
随时随地看视频慕课网APP
我要回答