我遇到的问题是在第3步。我想将新实例命名为“found [i]”,其中i对于每个预订都会增加:
ConflictingBooking found = new ConflictingBooking();
found.BookingNumber = conflictingBookingNumber;
found.BookingStarts = conflictingBookingDT;
conflictingBookings.Add(found);
在上面的代码中,我需要以编程方式替换'found'。
虽然我很欣赏一个简单的代码片段,但我也想阅读一些参考资料,所以我知道我在做什么:-)。我只是不知道如何谷歌我的问题。
似乎我还没有完全清楚 - 这是适当的代码:
dbManager.Open();
dbManager.ExecuteReader(CommandType.Text, string.Format("SELECT BookingDate, {0} FROM BTable WHERE Court IN {1} AND BookingDate IN ({2})", columns, facilityIDs, bookingDates));
using (IDataReader rdr = dbManager.DataReader)
{
decimal conflictingBookingNumber = 0;
DateTime conflictingBookingDT;
object result = null;
while (rdr.Read())
{
for (int i = 0; i < requestedColumnNames.Count; i++)
{
result = dbManager.DataReader[requestedColumnNames[i].ToString()];
if (result != null)
conflictingBookingNumber = Convert.ToDecimal(result);
result = dbManager.DataReader["BookingDate"];
if (result != null)
conflictingBookingDT = Convert.ToDateTime(result);
if (conflictingBookingNumber > 0)
{
int next = conflictingBookings.Count + 1;
ConflictingBooking found = new ConflictingBooking();
found.BookingNumber = conflictingBookingNumber;
found.BookingStarts = conflictingBookingDT;
// conflictingBookings is a List<conflictingBooking>
conflictingBookings.Add(found);
}
}
}
}
希望澄清我的问题。
答案 0 :(得分:2)
我认为你所要找的就是把你的代码放在for循环中。我可能完全误解了你,但似乎你想要做这样的事情
int i = 0;
foreach(var result in resultSet)
{
ConflictingBooking found = new ConflictingBooking();
found.BookingNumber = conflictingBookingNumber;
found.BookingStarts = conflictingBookingDT;
found.Name = "found["+i++ +"]";
conflictingBookings.Add(found);
}
如果那不是您想要的,请澄清您的问题
答案 1 :(得分:1)
变量名只是为了方便程序员而存在,并且在运行时并不存在。您无法在运行时生成实际变量。
因为您正在填充列表,所以您应该拥有根据索引生成“名称”以显示目的所需的所有数据。例如:
for(int i = 0; i < conflictingBookings.Length; i++)
{
Console.WriteLine("found[" + i + "]: " + found.BookingNumber);
}
答案 2 :(得分:0)
简单解决方案:将循环计数器添加到构造函数中:
ConflictingBooking found = new ConflictingBooking(i);
然后添加一个方法(或覆盖ToString()
)以返回字符串连接的实例名称。