gpt4 book ai didi

C# 不需要重复类实例化吗?

转载 作者:行者123 更新时间:2023-11-30 20:24:24 25 4
gpt4 key购买 nike

我有主课:

class MainClass
{
public static void Main()
{
InputForm InputForm1 = new InputForm();
InputForm1.ShowDialog(); // show interface to prompt user
}
}

这只是调用一个窗口窗体。这有以下类:

public partial class InputForm : Form
{
public InputForm()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
// do some calculation and then create a dictionary of items

for (int n = 1; n <= dict.Count; n++) // loop through items
{
LengthClass theLength = new LengthClass();
dict[n].calculatedLength = theLength.calcLength(arg1, arg2, dict[n].speed);

}
}
}

单击该按钮后,程序会对从电子表格中读取的数据进行一些计算,并将结果保存到字典中。每个元素都是一种动物,我有一些属性存储在字典中(例如,在键“狗”下,我有狗的平均体重、平均速度等)。使用速度和两个默认参数(arg1 和 arg2),我必须调用类 LengthClass 的方法以获得特定动物在 arg1 小时和 arg2 分钟内覆盖的估计长度。LengthClass 是这样的:

class LengthClass
{
public double calcLength(double arg1, double arg2, double speed)
{
// do some calculation
return x;
}
}

现在我的疑惑是如何更好地设计代码。当遍历字典中的每个键时,我每次都实例化一个 LengthClass 并调用它的方法。这是正确的做法吗?我想将计算长度的方法与 Windows 窗体中的代码分开,以便在必要时更容易更改它。但我认为每次都实例化该类可能会减慢代码速度,更好的设计可以使代码快速且易于阅读。有什么建议吗?

感谢下面的回答,似乎将方法 calcLength 声明为静态可以解决问题并避免重复实例化 LengthClass。但是如果 LengthClass 有一个额外的方法,比如 calcLength2(),为了执行计算需要调用一个新类的方法,比如 helpClass,我是否需要将 helpClass 的方法声明为静态的,以避免 helpClass 的实例化在 LengthClass 中从我的 calcLength2() 调用它的方法时?

最佳答案

在您提供的示例中,calcLength 方法不需要是实例方法,因为它不使用 LengthClass 的任何字段。您可以通过将此方法设为静态来避免或完全创建对象:

class LengthClass
{
public static double calcLength(double arg1, double arg2, double speed)
{
// do some calculation
return x;
}
}

那么你可以这样调用它:

public partial class InputForm : Form
{
public InputForm()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
// do some calculation and then create a dictionary of items

for (int n = 1; n <= dict.Count; n++) // loop through items
{
dict[n].calculatedLength = LengthClass.calcLength(arg1, arg2, dict[n].speed);
v = myPort[n].midVol;
}
}
}

关于C# 不需要重复类实例化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26906670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com