C# 将多个变量保存到类

C# 将多个变量保存到类,c#,C#,我对编程相当陌生,我正试着把头脑集中在课堂上。我创建了一个类,如下所示: public class HistoricalEvents { public DateTime historicDate { get; set; } public string historicEvent { get; set; } } 我希望能够进入MySQL数据库,提取多个事件,然后在屏幕上显示这些事件。如何从MySQL创建多个HistoricaleEvents

我对编程相当陌生,我正试着把头脑集中在课堂上。我创建了一个类,如下所示:

    public class HistoricalEvents
    {
        public DateTime historicDate { get; set; }
        public string historicEvent { get; set; }
    }

我希望能够进入MySQL数据库,提取多个事件,然后在屏幕上显示这些事件。如何从MySQL创建多个HistoricaleEvents,然后遍历它们以将它们显示在屏幕上?

首先,您需要一个表示单个事件的类,最好用单数形式命名为eg HistoricaleEvent,而不是HistoricaleEvents

然后您可以创建如下列表:

foreach (HistoricalEvent historicalEvent in historicalEvents)
{
    // "historicalEvent" contains the current HistoricalEvent :)
}
从MySQL数据库创建对象要复杂得多。如果您想加入,请尝试Microsoft提供的服务,也许还可以研究一下,但我建议您先熟悉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"
}

首先,您需要一个表示单个事件的类,最好用单数形式命名,例如HistoricalEvent,而不是HistoricalEvents

然后您可以创建如下列表:

foreach (HistoricalEvent historicalEvent in historicalEvents)
{
    // "historicalEvent" contains the current HistoricalEvent :)
}
从MySQL数据库创建对象要复杂得多。如果您想加入,请尝试Microsoft提供的服务,也许还可以研究一下,但我建议您先熟悉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"
}
这将使用ADO.Net提供程序:

var list = new List<HistoricalEvent>();

using (var cn = new MySqlConnection())
{
    cn.Open();

    var sql = "SELECT Date, Event FROM HistoricalEvents";
    using(var cm = new MySqlCommand(sql, cn))
    using(var dr = cm.ExecuteReader())
    {
        while (dr.Read)
            list.Add(new HistoricalEvent
            {
                historicDate = dr.GetDate(0), 
                historicEvent= dr.GetString(1)
             });

    }
}

foreach (var item in list)
    Console.WriteLine("{0}: {1}",item.historicDate,item.historicEvent);
这将使用ADO.Net提供程序:

var list = new List<HistoricalEvent>();

using (var cn = new MySqlConnection())
{
    cn.Open();

    var sql = "SELECT Date, Event FROM HistoricalEvents";
    using(var cm = new MySqlCommand(sql, cn))
    using(var dr = cm.ExecuteReader())
    {
        while (dr.Read)
            list.Add(new HistoricalEvent
            {
                historicDate = dr.GetDate(0), 
                historicEvent= dr.GetString(1)
             });

    }
}

foreach (var item in list)
    Console.WriteLine("{0}: {1}",item.historicDate,item.historicEvent);