我正在尝试创建一类列表
public class comparisonData
{
public List<string> Tables { get; set; }
public List<string> Constraints { get; set; }
public List<string> StoredProcs { get; set; }
public List<string> Views { get; set; }
public List<string> Functions { get; set; }
public List<string> Columns { get; set; }
public List<string> Synonyms { get; set; }
public List<string> NotNullables { get; set; }
}
然后实例化该类作为列表
List<comparisonData> cList = new List<comparisonData>();
我的最终目标是要列出几个不同的数据库名称,每个数据库名称都有一个包含上述数据库表名称,列,约束等的列表。
但是,当我尝试填充列表时,我收到“索引超出范围。必须为非负数并且小于集合的大小”错误
while(reader.Read())
{
cList[0].Tables.Add(reader.GetString(0));
}
我在实例化错误吗?还是此列表只是不好的代码,我应该为最终目标追求不同的方法吗?
首先,使用适当的代码命名类,并在构造函数上为示例命名集合:
public class ComparisonData
{
public List<string> Tables { get; set; }
public List<string> Constraints { get; set; }
public List<string> StoredProcs { get; set; }
public List<string> Views { get; set; }
public List<string> Functions { get; set; }
public List<string> Columns { get; set; }
public List<string> Synonyms { get; set; }
public List<string> NotNullables { get; set; }
public ComparisonData()
{
Tables = new List<string>();
Constraints = new List<string>();
// other properties...
}
}
在循环中,只需从中创建一个对象ComparisonData
并在属性列表中设置一些值即可,例如:
List<ComparisonData> cList = new List<ComparisonData>();
while(reader.Read())
{
ComparisonData c = new ComparisonData();
c.Tables.Add(reader.GetString(0));
// other properties
// since it is a List, just call the Add method and pass the object
cList.Add(c);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句