[英]C# recurring class instantiation unnecessary?
我有主課:
class MainClass
{
public static void Main()
{
InputForm InputForm1 = new InputForm();
InputForm1.ShowDialog(); // show interface to prompt user
}
}
只需調用Windows窗體。 此類具有以下類別:
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);
}
}
}
單擊該按鈕時,程序將對從電子表格讀取的數據進行一些計算,並將結果保存到詞典中。 每個元素都是動物,我具有一些要存儲在字典中的屬性(例如,在“ Dog”鍵下,我具有狗的平均體重,平均速度等)。 使用速度和兩個默認參數(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;
}
}
}
進一步擴展Sam Holder的好答案,看來您的LengthClass最好標記為static本身。 感覺您不應該創建LengthClass
實例,特別是因為它不包含任何持久成員。 用類最好描述的UML准則屬性可能會有所幫助。
static class LengthClass
{
public static double calcLength(double arg1, double arg2, double speed)
{
// do some calculation
return x;
}
}
和用法:
private void button1_Click(object sender, EventArgs e)
{
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;
}
}
另一個提示是,如果您確實需要LengthClass作為對象,則最好在for循環范圍之外實例化它,尤其是在創建成本很高的情況下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.