我创建了以下内容:
public class Members
{
public string Member { get; set; }
public string Number{ get; set; }
public Members(string _member, string _num)
{
Member= _member;
Number = _num;
}
}
并从另一个类调用它:
int countRows = 0;
SqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
countRows += 1;
Members sample1 = new Members ("170128", "REG");
Members sample2 = new Members ("170129", "REG");
Members sample3 = new Members ("170130", "TAQ");
List<Members> listOfMembers = new List<Members>();
listOfMembers.Add(sample1);
listOfMembers.Add(sample2);
listOfMembers.Add(sample3);
foreach (var item in listOfMembers)
{
Response.Write("Member: " + item.Member + " Number: " + item.Number +"<br />");
}
}
dataReader.Close();
dataReader.Dispose();
con.Close();
有效。除此之外,我想动态创建和添加样本,例如:
Members sample + countRows = new Members(datareader["value1"], datareader["value2"])
这不起作用。 int countRows和对象样本不兼容。我如何实现类似的东西,以便动态创建sample1,sample2等,并同样添加到列表中?
答案 0 :(得分:2)
使用Collection或Array来保存您的类
List<Members> sample = new List<Members>();
在循环中做
sample.Add(new Members(dataReader.GetInt(0), dataReader.GetInt(1)))
注意:GetInt()是我的猜测。使用GetString()或任何类型 或者以原生格式
sample.Add(new Members(dataReader["columnName"], dataReader["columnName"]))