我对编程还很陌生,正在努力全神贯注于类(class)。我创建了如下类:
public class HistoricalEvents
{
public DateTime historicDate { get; set; }
public string historicEvent { get; set; }
}
我希望能够进入 MySQL 数据库,提取多个事件,然后将这些事件显示到屏幕上。您如何从 MySQL 创建多个 HistoricalEvents,然后遍历它们以将它们显示在屏幕上?
最佳答案
首先,您需要一个表示单个事件的类,最好以单数形式命名(例如 HistoricalEvent
而不是 HistoricalEvents
)。
然后你可以创建一个List<HistoricalEvent>
像这样:
public class HistoricalEvent
{
public DateTime historicDate { get; set; }
public decimal historicEvent { get; set; }
}
List<HistoricalEvent> historicalEvents = new List<HistoricalEvent>();
historicalEvents.Add(new HistoricalEvent());
// ... etc etc ...
一旦你有了你的列表,你就可以像这样迭代它:
foreach (HistoricalEvent historicalEvent in historicalEvents)
{
// "historicalEvent" contains the current HistoricalEvent :)
}
从 MySQL 数据库创建对象要复杂得多。如果您想加入,请尝试 this tutorial (由 Microsoft 提供),或许可以查看 linq to objects , 但我建议先熟悉 C# :)
编辑:
这听起来有点简洁,所以这里有一个类似的例子:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
List<Person> people = new List<Person>();
people.Add(new Person()
{
Name = "Dave",
Age = 43
});
people.Add(new Person()
{
Name = "Wendy",
Age = 39
});
foreach (Person person in People)
{
Console.WriteLine(person.Name) // "Dave", then "Wendy"
}
关于c# - 将多个变量保存到类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35446969/