![](/img/trans.png)
[英]How can I pass a class into a method so the method can get a reference to that class and act upon it?
[英]How would I modify this method so I can reference or pass the data of each individual loop?
我想知道如何引用每個數據循環,以便我可以將它傳遞給文本框。 如果有5個循環,我如何才能選擇僅在我的主窗體上的文本框中顯示的第3個循環? 我已經添加了m_intNumberofEvents來計算它所做的循環次數,但我不知道如何連接它或它是否工作。 請幫忙! 謝謝!
public List<Event> ExtractData(DateTime dtmDay)
{
int intChosenDay = dtmDay.Day;
m_intNumberofEvents = 0;
int intFileDay;
StreamReader textIn = new StreamReader(
new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));
//create the list
List<Event> events = new List<Event>();
string[] lines = File.ReadAllLines(path);
for (int index = 4; index < lines.Length; index += 5)
{
Event special = new Event();
special.Day = Convert.ToInt32(lines[index - 4]);
special.Time = (lines[index - 3]);
special.Price = Convert.ToDouble(lines[index - 2]);
special.StrEvent = lines[index - 1];
special.Description = lines[index];
events.Add(special);
m_intNumberofEvents++;
}
textIn.Close();
return events;
}
我的要求可能有問題,但是在循環之后你將有一個Event
對象列表,如果你只想使用第3個項目(即第3個循環中填充的那個)那么你可以從列表中拉出它就像這樣:
Event thridEvent = events[2];//NOTE: 0 based index
//do something with the event, like populate a textbox
您可以訪問所需列表中的任何項目,0 = 1st,1 = 2nd,2 = 3rd等...
您也不需要計算它所執行的循環次數,您可以從列表的長度獲得相同的值:
int numberOfLoops = events.Count();
還值得一提的是,如果輸入數據不符合應用程序崩潰的預期格式,則無法對輸入文件進行驗證。
您可以將邏輯提取到單獨的方法中,以簡化從string []數組中提取Event對象:
Event ReadEventFromIndex(string[] lines, int index)
{
index = 4 + index * 5;
Event special = new Event();
special.Day = Convert.ToInt32(lines[index - 4]);
special.Time = (lines[index - 3]);
special.Price = Convert.ToDouble(lines[index - 2]);
special.StrEvent = lines[index - 1];
special.Description = lines[index];
return special;
}
注意我如何通過執行index = 4 + index * 5;
將邏輯索引轉換為訪問lines[]
所需的偏移量index = 4 + index * 5;
然后,如果你想要第3項(當然是邏輯索引2,當然不是3),你可以這樣做:
var thirdEvent = ReadEventFromIndex(lines, 2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.