[英]how to dynamically create struct instances and store them in a list?
我有一个硬件任务,说要创建一个 win 表单应用程序,让用户点击 2018 年 1 月的任何一天。然后显示关于当天天气的四条数据。
脚步:
首先读取包含每天天气数据(例如 1/13/2018;0;36;13)的 weather.txt 文件,并将 4 条数据拆分为 struct 的四个字段并创建当天的实例。 然后将这一天存储在一个列表中。
我的问题:
如何像这样动态地创建结构的实例。 我想到的唯一一件事就是在每个月的每一天循环更改 var 名称,例如[structObj] d[i] = new [structObj](string date, int precipitation, int temp);
其中 [i] 使用循环更改名称,然后我很容易将几个月的结构填充到我的列表中。 这不起作用:(
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Weather_data
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
struct WeatherData
{
private string date { get; set; }
private int precipitation { get; set; }
private int hiTemp { get; set; }
private int lowTemp { get; set; }
public WeatherData(string date, int precipitation, int hiTemp, int lowTemp)
{
this.date = date;
this.precipitation = precipitation;
this.hiTemp = hiTemp;
this.lowTemp = lowTemp;
}
}
private void button1_Click(object sender, EventArgs e)
{
//change FILE PATH for weather.txt here--->
string[] lines = File.ReadAllLines(@"C:\Users\sethr\Desktop\C#\M9SPabst\Weather data\Weather data\weather.txt");
for(int i = 0; i < lines.Length; i++)
{
string[] data = lines[i].Split(';');
WeatherData d = new WeatherData(data[0],
Convert.ToInt32(data[1]),
Convert.ToInt32(data[2]),
Convert.ToInt32(data[3]));
}
}
}
}
假设 FileReadsAllLines 正确读取,您会将列表添加到您的代码中。 然后添加每个元素。 您将需要一个组件来在 UI 中显示列表。
List<WeatherData> wheatherDataList = new List<WeatherData>();
private void button1_Click(object sender, EventArgs e)
{
//change FILE PATH for weather.txt here--->
string[] lines = File.ReadAllLines(@"C:\Users\sethr\Desktop\C#\M9SPabst\Weather data\Weather data\weather.txt");
for (int i = 0; i < lines.Length; i++)
{
string[] data = lines[i].Split(';');
WeatherData d = new WeatherData(data[0],
Convert.ToInt32(data[1]),
Convert.ToInt32(data[2]),
Convert.ToInt32(data[3]));
wheatherDataList.Add(d);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.