简体   繁体   English

C#循环类实例化是不必要的吗?

[英]C# recurring class instantiation unnecessary?

I have the main class: 我有主课:

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

that simply calls a windows form. 只需调用Windows窗体。 This has the following class: 此类具有以下类别:

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); 

        }
    }
}

When the button is clicked, the program does some calculation on data that are read from a spreadsheet and save results into a dictionary. 单击该按钮时,程序将对从电子表格读取的数据进行一些计算,并将结果保存到词典中。 Each element is an animal and I have some properties that I store in the dictionary (eg under the key "Dog" I have an average weight of dogs, an average speed, etc.). 每个元素都是动物,我具有一些要存储在字典中的属性(例如,在“ Dog”键下,我具有狗的平均体重,平均速度等)。 Using the speed and two default arguments (arg1 and arg2) I have to call the method of the class LengthClass in order to get the estimated length that is covered by the specific animal in arg1 hours and arg2 minutes. 使用速度和两个默认参数(arg1和arg2),我必须调用LengthClass类的方法,以便获得特定动物在arg1小时和arg2分钟内覆盖的估计长度。 The LengthClass is like this: LengthClass是这样的:

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

Now my doubt is how to better design the code. 现在我的疑问是如何更好地设计代码。 When looping through each key in the dictionary I instantiate each time a LengthClass and call its method. 当遍历字典中的每个键时,我每次实例化LengthClass并调用其方法。 Is this the right things to do? 这是正确的做法吗? I would like to keep the method to calculate the length separate from the code in the windows form so that it is easier to change it if necessary. 我想保持计算长度的方法与Windows窗体中的代码分开,以便在必要时更容易进行更改。 But I think that instantiating the class everytime might slow down the code and that a better design could keep the code fast and easy to read. 但是我认为每次实例化该类都可能会使代码变慢,并且更好的设计可以使代码保持快速且易于阅读。 Any suggestion? 有什么建议吗?

Thanks to answers below, it seems that declaring the method calcLength as static would solve the problem and avoid the need of a recurring instantiation of LengthClass. 由于以下答案,似乎将calcLength方法声明为静态方法可以解决此问题,并避免需要对LengthClass进行重复实例化。 But if LengthClass has an additional method, say calcLength2(), that in order to perform the calculations need to call the methods of a new class, say helpClass, do I need to declare methods of helpClass as static in order to avoid instantiations of helpClass when calling its methods from my calcLength2() in LengthClass? 但是,如果LengthClass还有一个额外的方法,例如calcLength2(),则为了执行计算,需要调用一个新类的方法(例如helpClass),我是否需要将helpClass的方法声明为静态方法,以避免实例化helpClass从LengthClass中的calcLength2()调用其方法时?

From the example you have given your calcLength method doesn't need to be an instance method, as it doesn't use any fields of the LengthClass . 在示例中,您给出的calcLength方法不必是实例方法,因为它不使用LengthClass任何字段。 You could avoid or the object creation altogether by making this method static: 您可以通过将此方法设为静态来避免或完全创建对象:

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

then you can call it like this: 那么您可以这样称呼它:

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;
        }
    }
}

Further expanding on Sam Holder's good answer, it seems that your LengthClass would better off marked as static itself. 进一步扩展Sam Holder的好答案,看来您的LengthClass最好标记为static本身。 It feels like you shouldn't be creating instances of LengthClass especially since it doesn't contain any persistent members. 感觉您不应该创建LengthClass实例,特别是因为它不包含任何持久成员。 UML guidelines for attributes which are best described with classes may help. 用类最好描述的UML准则属性可能会有所帮助。

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

and usage: 和用法:

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;
    }
}

Another tip is if you do need LengthClass to be an object, it would be better to instantiate it outside the scope of the for-loop, especially if it is expensive to create. 另一个提示是,如果您确实需要LengthClass作为对象,则最好在for循环范围之外实例化它,尤其是在创建成本很高的情况下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM