![](/img/trans.png)
[英]InvalidOperationException was unhandled by user code - error CS0029: Cannot implicitly convert type 'string' to 'string[]'
[英]Arraylist item does not take a string as an input error code : CS0029
ArrayList a = new ArrayList();
a[i] = txtSifre.Text; //ERROR CS0029
我想將來自文本框的字符串數據存儲到 ArrayList 中。但是,我遇到了一個轉換錯誤:無法在 C# 中將類型“string”隱式轉換為“system.collections.arraylist”
這是完整的代碼:
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++;
}
}
正如 Martheen 提到的,最好使用 List。
例子:
var a = new List<string>();
a.Add(txtSifre.Text);
但是,我也會關注某些要點。
1. 對openwith
進行雙重foreach
我認為第一個循環沒有用,你可以刪除它,當然不刪除它的內容。
//foreach (var item in openwith) //DELETE THIS
//{
foreach (DictionaryEntry de in openwith)
{
listBox1.Items.Add($"User Name : {de.Key} \t Password : {de.Value}");
}
//}
2. If/Foreach塊
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!!");
}
}
}
對我來說,這似乎很復雜,但我可能不了解您要嘗試做的所有事情。
在這里我會給你更多的建議:
List.Count
屬性來計算列表中的項目數。 示例: if (a.Count > 1) {... }
List.Contains
方法檢查項目是否在列表中。 示例: if (a.Contains(txtSifre.Text)) {... }
希望對你有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.