索引超出了允许的范围.为什么?
本文关键字:范围 为什么 索引 | 更新日期: 2023-09-27 18:26:53
我的C#代码有问题,我无法解决这个问题。所以,我的问题是,当我尝试登录时会出现异常。没有任何固定元素对象。代码中的问题在哪里?例外:
索引超出了允许的范围。参数:索引
代码:
public dbresult.GetSome Get(Oneword.dbcon conn, string tablename) {
string constring = "Server=" + conn.Host + ";Database=" + conn.Database + ";Uid=" + conn.Username + ";Pwd=" + conn.Password;
int i,im=0;
Oneword.dbresult.GetSome result = new dbresult.GetSome();
MySqlConnection connection = new MySqlConnection(constring);
connection.Open();
try {
MySqlDataReader oszlopok_cmd = null;
MySqlDataReader sorok_cmd = null;
DataTable oszlopok = null;
MySqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM "+tablename;
// Oszlopok lekérése
oszlopok_cmd = cmd.ExecuteReader(CommandBehavior.SchemaOnly);
oszlopok = oszlopok_cmd.GetSchemaTable();
oszlopok_cmd.Close();
List<string> columns = new List<string>();
foreach (DataRow col in oszlopok.Rows) {
columns.Add(col.Field<String>("ColumnName"));
}
// Sorok lekérése, és tárak feltöltése
sorok_cmd = cmd.ExecuteReader();
while (sorok_cmd.Read()) {
i = result.AddNewDir();
foreach (string clomone in columns) {
result.AddKeyValue(i, clomone, sorok_cmd.GetString(im));
im++;
}
}
}
finally {
connection.Close();
}
return result;
}
public class dbresult {
public class GetSome {
private List<Dictionary<string, string>> dirlistem = new List<Dictionary<string, string>>();
private int cuID = 0;
public void AddKeyValue(int dirID, string key, string value){
dirlistem[dirID][key] = value;
}
public int AddNewDir() {
Dictionary<string,string> added = new Dictionary<string,string>();
cuID++;
return cuID - 1;
}
public Dictionary<string, string> GetDir(int dirID) {
return dirlistem[dirID];
}
public void ModifyValue(int dirID, string key, string value) {
dirlistem[dirID][key] = value;
}
}
}
您没有将创建的字典添加到列表中:
public int AddNewDir() {
Dictionary<string,string> added = new Dictionary<string,string>();
// ***
dirlistem.Add(added);
// ***
cuID++;
return cuID - 1;
}
因此,任何有dirlistem[dirID]
的地方都会抛出异常。
此外,GetSome
类中不需要cuID
成员。简单
return dirlistem.Count - 1;
来自CCD_ 4。