c# - 将多个变量保存到类

标签 c#

我对编程还很陌生,正在努力全神贯注于类(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/

相关文章:

c# - ElasticSearch NEST 7.x 将项目附加到现有文档对象数组属性

c# - 为什么 Office Interop 引用在 VS 2010 中显示错误

c# - 如何从 .Net core 2.0 中的 HttpContext 获取访问 token

c# - 为什么这个 LINQ 查询没有返回正确的日期?

c# - 为什么 "async Task"方法的返回值不是任务

c# - 从可枚举中获取下一个 N 个元素

c# - 如何使用 C# 中的一个函数将 SqlDependency 和 SignalR 与 2 个不同的数据库一起使用?

c# - 如何绘制一个圆形按钮并在其上制作标签

c# - 有没有办法从 System.Windows.Forms.HtmlElement 转换为 mshtml.IHTMLElemenet3?

c# - 屏幕截图质量比正常差