vs 2019中的行动/功能代表的问题

发布于 2025-01-22 16:49:02 字数 955 浏览 2 评论 0原文

我试图制作一个程序,该程序从控制台读取数字序列,然后仅以分类顺序打印偶数。问题是,当我尝试从代表中的数组中删除数字时,它不起作用。我知道制作程序的方法有很多,但是我想了解更多有关代表和事件的信息。如果你们可以帮助我解决这个问题(或对该主题有任何信息),那将是非常有帮助的。谢谢!!!

我的代码:

 Func<int, bool> checkIfEven = num => num % 2 == 0;

        Action<int[]> sortArray = arr => Console.WriteLine(arr.Max() + " ");

        Func<List<int>, int> findMaxIndex = num => num.IndexOf(num.Max());    
        
        int[] numbers = Console.ReadLine().Split(" ").Select(int.Parse).Where(checkIfEven).ToArray();

        Action<List<int>> removeMax = list => list.RemoveAt(findMaxIndex(numbers.ToList()));

        while (numbers.Length>0)
        { 
            sortArray(numbers);
            removeMax(numbers.ToList());
        }

“在此处输入图像描述”

I tried to make a program that reads from the console a sequence of numbers and then prints only the even ones in sorting order. The problem is that when I try to remove a number from the array in the delegate it does NOT work. I know there are much simpler ways of making the program, but I want to learn more about delegates and events. If you guys can help me with this(or have any information about the topic) it would be extremely helpful. Thanks!!!

My code:

 Func<int, bool> checkIfEven = num => num % 2 == 0;

        Action<int[]> sortArray = arr => Console.WriteLine(arr.Max() + " ");

        Func<List<int>, int> findMaxIndex = num => num.IndexOf(num.Max());    
        
        int[] numbers = Console.ReadLine().Split(" ").Select(int.Parse).Where(checkIfEven).ToArray();

        Action<List<int>> removeMax = list => list.RemoveAt(findMaxIndex(numbers.ToList()));

        while (numbers.Length>0)
        { 
            sortArray(numbers);
            removeMax(numbers.ToList());
        }

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半暖夏伤 2025-01-29 16:49:02

问题在此行中:

removemax(numbers.tolist());

此调用:numcks.tolist()数字数组,因此当removemax被称为时,它将从列表中删除一个元素,该元素是 Array的副本数字数组本身可能是故意的。

The problem is in this line:

removeMax(numbers.ToList());

This call: numbers.ToList() creates a new list from numbers array so when removeMax is called it removes an element from a list which is a copy of array numbers not the numbers array itself as it was probably intended.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文