C# WinForm - 使用类中的方法通过给定 3 个数字计算小时数
本文关键字:数字 小时 计算 WinForm 方法 | 更新日期: 2023-09-27 18:30:33
我正在创建一个简单的距离计算器。我有一个带有 2 个组合框的窗口表单。第一个组合框具有默认位置,即 Place1,第二个组合框的值为 Place1、Place2 和 Place3。
这是我在课堂上的代码。
public class classDistance
{
public string Places { get; set; }
public int DistanceKm { get; set; }
public static void Hours() {
List<string> Cities = new List<string>();
Cities.Add("Place1");
Cities.Add("Place2");
Cities.Add("Place3");
List<int> DestinationKm = new List<int>();
DestinationKm.Add(10); // Place1 = 10Km
DestinationKm.Add(20); // Place2 = 20Km
DestinationKm.Add(30); // Place3 = 30Km
return;
}
}
//Place1 has the speed of 80kmph.
当用户单击表单中的按钮时,它将从方法类 classDistance 计算小时数
// Inside my form
public Form1()
{
InitializeComponent();
}
classDistance classname = new classDistance();
private void button1_Click(object sender, EventArgs e)
{
if(comboBox1.Text == "Place1"){
// call the method on the classname if the user click the button and calculate the hours
}
}
我该怎么做?
提前谢谢你!
由于您将方法Hours()
静态的,因此您可以简单地由类调用它,而无需创建任何实例,如下所示:
private void button1_Click(object sender, EventArgs e)
{
ClassDistance.Hours();
}
但是现在您的方法只是填充列表,而不是实际计算小时数。
上级:我认为最好使用字典来存储和获取数据:
var citiesDistance = new Dictionary<string, int>
{
{"Place1", 10},
{"Place2", 20},
{"Place3", 30}
};
然后,您可以通过地名获得适当的值,例如:
var name = "Place2";
var length = citiesDistance[name];
之后,您可以计算到达该地点所需的小时数:
var speed = 80;
var hours = length/speed;
希望,我正确理解了你的问题)
目前,您有一个地点列表和一个彼此之间并不真正相关的距离列表。
我要做的是创建一个包含地名和距离的新类,例如:
public class Destination
{
public string Name {get;set;}
public int DistanceKm {get;set;}
// ctor
public Destination(String name, int distanceKm)
{
Name = name;
DistanceKm = distanceKm;
}
public int getHours (int speed)
{
// do your calculation for the number of hours here
return hours;
}
}
然后,可以通过构造函数使用目标的名称和距离填充目标,并使用 getHours 方法根据传入目标的速度返回小时数。
如果要处理多个目标,也可以创建列表