我正在处理Windows窗体应用程序,我遇到了问题。在GetDataFromFile方法中,我返回了2个集合,但是在buttton上开始我如何获取它们并如图所示使用它们。
提前谢谢你,如果我的问题很愚蠢,我很抱歉,但我是新手,无法弄清楚
public Tuple<List<string>,List<string>> GetDataFromFile()
{
XDocument doc = XDocument.Load("NotificationTasks.xml");
var dates = doc.Descendants("Date");
var hours = doc.Descendants("Time");
var hoursCollection = new List<string>();
var dateCollection = new List<string>();
foreach (var date in dates)
{
dateCollection.Add(date.Value);
}
foreach (var hour in hours)
{
hoursCollection.Add(hour.Value);
}
return Tuple.Create(hoursCollection,dateCollection);
}
private void btnStart_Click(object sender, EventArgs e)
{
//here I must use the two collections from GetDataFromFile()
foreach (var dates in hoursCollection)
{
if (dates == DateTime.Now.Date)
{
foreach (var hours in hoursCollection)
{
StartNotificating(new TimeSpan(hours));
}
}
}
}
答案 0 :(得分:2)
您可以定义自己的类来返回数据:
public class FileData
{
public FileData(IEnumerable<string> hours, IEnumerable<string> dates)
{
Hours = hours;
Dates = dates;
}
public IEnumerable<string> Hours { get; }
public IEnumerable<string> Dates { get; }
}
更改用于获取数据的方法:
public FileData GetDataFromFile()
{
// read file etc...
return new FileData(hoursCollection, datesCollection);
}
您的处理程序是:
private void btnStart_Click(object sender, EventArgs e)
{
FileData fileData = GetDataFromFile();
var hoursCollection = fileData.Hours;
var dateCollection = fileData.Dates;
}
使用包含属性名称的类可以减少混淆Item1
的{{1}}和Item2
的可能性。
答案 1 :(得分:0)
您也可以使用元组从方法接收数据类型。
参考:https://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx
public Tuple<List<string>,List<string>> GetDataFromFile()
{
XDocument doc = XDocument.Load("NotificationTasks.xml");
var dates = doc.Descendants("Date");
var hours = doc.Descendants("Time");
var hoursCollection = new List<string>();
var dateCollection = new List<string>();
foreach (var date in dates)
{
dateCollection.Add(date.Value);
}
foreach (var hour in hours)
{
hoursCollection.Add(hour.Value);
}
return Tuple.Create(hoursCollection,dateCollection);
}
private void btnStart_Click(object sender, EventArgs e)
{
//here I must use the two collections from GetDataFromFile()
Tuple<List<String>,List<String>> t = GetDataFromFile();
List<String> hoursCollection = t.Item1;
List<String> dateCollection = t.Item2;
foreach (var dates in hoursCollection)
{
if (dates == DateTime.Now.Date)
{
foreach (var hours in hoursCollection)
{
StartNotificating(new TimeSpan(hours));
}
}
}
}