gpt4 book ai didi

c# - 交换数组中的对象 - C#

转载 作者:行者123 更新时间:2023-11-30 14:41:53 24 4
gpt4 key购买 nike

在 C# 中,我有一个 MenuItem 数组。我尝试使用以下代码交换数组索引 2 和索引 3 中的两个对象,但没有成功:

MenuItem Temp = Items[2];  
Items[2] = Items[3];
Items[3] = Temp;

第二行和第三行不能在 C# 中运行一定是有原因的,我可能还不明白。有谁能再澄清一点吗?我是否必须更深入地单独交换对象中的每个属性?

已编辑 - 抱歉。看起来我在尝试清理代码以便发布时弄乱了代码。现在更正。

实际代码是:

MenuItem TempButton = MenuItems.Items[SelectedButton.CountId];  
MenuItems.Items[SelectedButton.CountId] = MenuItems.Items[SelectedButton.CountId + 1];
MenuItems.Items[SelectedButton.CountId + 1] = TempButton;

MenuItems.ItemsMenuItem

的数组

查看我放在 MenuItems.Items 上的 watch ,第 2 行或第 3 行没有任何反应。

MenuItems.Items 属性具有 get 和 set 函数,这可能是导致问题的原因...将进一步调查...

最佳答案

您正在将 Items[2] 设置为 Temp,这是 Items[2] 开始的,因此您实际上没有做任何事物。我不知道 SelectedButton.CountId 应该是什么。

但是如果你只想交换索引 2 和 3,你可以这样做:

Item Temp = Items[2];
Items[2] = Items[3];
Items[3] = Temp;

关于c# - 交换数组中的对象 - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3614785/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com