C#中ArrayList赋值遇CS0029错误:无法隐式转换string为ArrayList
问题:C#中无法将string隐式转换为ArrayList(错误CS0029)
我想把文本框txtSifre.Text中的字符串存入ArrayList,但遇到了转换错误:无法将类型‘string’隐式转换为‘System.Collections.ArrayList’,错误代码CS0029。
错误代码片段:
ArrayList a = new ArrayList(); a[i] = txtSifre.Text; //ERROR CS0029
完整代码:
int i = 0; ArrayList a = new ArrayList(); private void btnEkle_Click(object sender, EventArgs e) { Hashtable openwith = new Hashtable(); openwith.Add(txtKullaniciAdi.Text, txtSifre.Text); foreach (var item in openwith) { foreach (DictionaryEntry de in openwith) { listBox1.Items.Add($"User Name : {de.Key} \t Password : {de.Value}"); } } a[i] = txtSifre.Text; //ERROR CS0029 !! if(i>=1) { for (int J = 1; J < 2; J++) { if (a[J - 1].ToString() == a[J].ToString()) { MessageBox.Show("You can not enter the same password again!!"); } } } i++; }
解决方案
错误原因
ArrayList的索引赋值a[i] = ...要求索引i对应的位置已存在元素,但你初始化的ArrayList是空的,直接用索引赋值会触发类型不匹配错误(本质是索引越界导致的编译器误判)。
修复步骤
- 用
Add方法添加元素
向空ArrayList添加元素必须使用Add方法,而不是直接索引赋值:
a.Add(txtSifre.Text); // 替换原来的a[i] = txtSifre.Text;
- 调整重复密码检查逻辑
使用Add后,无需单独维护i变量,直接通过集合长度判断并获取元素:
ArrayList a = new ArrayList(); private void btnEkle_Click(object sender, EventArgs e) { Hashtable openwith = new Hashtable(); openwith.Add(txtKullaniciAdi.Text, txtSifre.Text); // 简化嵌套循环,避免重复添加数据 foreach (DictionaryEntry de in openwith) { listBox1.Items.Add($"用户名 : {de.Key} \t 密码 : {de.Value}"); } string newPwd = txtSifre.Text; a.Add(newPwd); // 检查与上一个密码是否重复 if (a.Count >= 2) { string lastPwd = a[a.Count - 2].ToString(); if (lastPwd == newPwd) { MessageBox.Show("不能重复输入相同的密码!"); // 可选:移除刚添加的重复密码 a.RemoveAt(a.Count - 1); } } }
- 推荐使用泛型集合
List<string>ArrayList是非泛型集合,存在装箱拆箱性能开销,C#中更推荐用List<string>存储字符串:
// 替换ArrayList为泛型集合 List<string> passwordList = new List<string>(); // 添加元素 passwordList.Add(txtSifre.Text); // 检查重复 if (passwordList.Count >= 2 && passwordList[passwordList.Count - 2] == txtSifre.Text) { MessageBox.Show("不能重复输入相同的密码!"); passwordList.RemoveAt(passwordList.Count - 1); }
内容的提问来源于stack exchange,提问作者PhysicsEngineer
相关产品推荐
相关产品推荐

