c# - 交换数组的两个特定成员的正确方法是什么?
问题描述
如果这个问题很无聊,我很抱歉,我只学习了 3 周。这有点压倒性,即使你像我一样做简单的事情。
所以我试图创建一个程序来管理“帐户”作为实践,并将用户和相应的密码放在两个单独的 .txt 文件中。每行相应地转换为用户或密码。我同时使用列表和数组,因为数组在某些情况下更容易使用,但列表可以有不同的长度。
我在为程序创建一个函数时遇到了一个问题,该函数将列表中的第一个用户“管理员”更改为一个用户,其 ID 以用户输入的形式给出。我读到了如何做到这一点,但我似乎失败了,因为预期的交换完全没有做任何事情。用户按原始顺序返回列表。也欢迎进一步观察我的代码为何混乱。
这是程序的这个函数的实际代码:
else if (input.Contains("changeadmin"))
{
foreach (string y in idKeysLocArray) //checks every line for username
{
if (input.Contains(y))
{
string[] idKeysLocArray2 = File.ReadAllLines(idKeysLoc); // creates new arrays in case .txt was updated by different function before
string[] passKeysLocArray2 = File.ReadAllLines(passKeysLoc);
static void Swap(ref string a, ref string b) // create function to swap two members of an array
{
string temp = a;
a = b;
b = temp;
}
Swap(ref idKeysLocArray2[0], ref idKeysLocArray2[Array.IndexOf(idKeysLocArray2, y)]); //using function to swap array members
Swap(ref passKeysLocArray2[0], ref passKeysLocArray2[Array.IndexOf(idKeysLocArray2, y)]);
var idKeysLocArray2List = idKeysLocArray2.ToList();
var passKeysLocArray2List = passKeysLocArray2.ToList();
foreach (string h in idKeysLocArray2List) // to check success
{
Console.WriteLine(h);
}
TextWriter w7 = new StreamWriter(idKeysLoc); // write swapped values to .txt file
foreach (string s in idKeysLocArray2List)
w7.WriteLine(s);
w7.Close();
TextWriter w8 = new StreamWriter(passKeysLoc);
foreach (string s in passKeysLocArray2List)
w8.WriteLine(s);
w8.Close();
}
}
}
解决方案
推荐阅读
- jhipster - 如何为 uaa(或网关?)设置永不过期的刷新令牌
- c++ - 如何更改窗体上所有控件的标题?[C++ 生成器]
- slick.js - 站点首次启动时未成功下载的光滑滑块之一
- css - Vuetify 自动完成,内部图标在聚焦时会改变颜色
- java - 如何在可执行 jar 文件中使用 SQLite?
- c# - 通用渲染局部视图 - 将 PropertyInfo 转换为具体对象
- excel - 如何比较 2 个海量/巨大/长列表并在一个字段中输出任何不匹配的结果
- ios - 单击每个部分时展开 tableview 部分
- javascript - 在 ASP.NET MVC 中使用 ADAL.JS
- javascript - 使用 crypto.subtle.digest("SHA-256", buffer) 散列大文件