我可以在循环内创建新对象吗? [英] Can I create new object inside loop?

查看:93
本文介绍了我可以在循环内创建新对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在循环内创建新对象吗?



请帮助我。



下面找到样本代码



哪一个好?



选项1或2或3。



谢谢!!!



我尝试了什么:



Can I Create New Object inside Loop?

Please assist me.

Below find sample code

Which one is good?

Option 1 or 2 or 3 .

Thank you !!!

What I have tried:

class A
{
    public void MethodA()
    {

        //--------------
    }
}


class B
{
    A a = new A();
    public void MethodB()
    {
        for (int i = 0; i < 500000; i++)
        {
            a.MethodA();
        }
    }
}


class B
{
    A a;
    public void MethodB()
    {
        for (int i = 0; i < 500000; i++)
        {
            a = new A();
            a.MethodA();
        }
    }
}


class B
{
    
    public void MethodB()
    {
        for (int i = 0; i < 500000; i++)
        {
            A a = new A();
            a.MethodA();
        }
    }
}

推荐答案

第二个和第三个选项创建500,000个新类对象A.不是一个好主意。
The second and third options create 500,000 new objects of class A. Not a very good idea.


你不能比较它们,它们做不同的工作,所以没有最好的或好的。

第一个例子

You can't compare them, they do different jobs, so there isn't a "best" or "good" one.
The first example
A a = new A();
public void MethodB()
{
    for (int i = 0; i < 500000; i++)
    {
        a.MethodA();
    }
}

每次都在类的同一个实例上调用MethodA。

第二个例子

Calls MethodA on teh same instance of the class every time.
The second example

A a;
public void MethodB()
{
    for (int i = 0; i < 500000; i++)
    {
        a = new A();
        a.MethodA();
    }
}

每次循环创建一个新实例,并在该实例上调用MethodA。



差异很微妙,但如果你想到汽车,那么在第一种情况下你买车,然后你每天开车上班。在第二种情况下,你每天都会买一辆新车开车上班,然后在一天结束时把它丢弃!



没有最好的或好的 - 对于某些方法,第一种是正确的,对于其他方法则是第二种。

Creates a new instance for each time around the loop, and calls MethodA on that instance.

The difference is subtle, but if you think about cars then in the first instance you buy a car, and you drive it to work each day. In the second instance, you buy a new car each day and drive it to work, then discard it at the end of the day!

There is no "best" or "good" in that - for some approaches the first is right, for others it's the second.


这篇关于我可以在循环内创建新对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆