Take a list from a method and use it in another method

血红的双手。 提交于 2019-12-16 18:05:04

问题


In my Orange class I have this method:

    public static List<Orange> AddOrange()
    {
        List<Orange> oranges = new List<Orange>();
        oranges.Add(new Orange() { Weight = 150, Measure = 6 });
        oranges.Add(new Orange() { Weight = 160, Measure = 6 });
        oranges.Add(new Orange() { Weight = 160, Measure = 6 });
        oranges.Add(new Orange() { Weight = 150, Measure = 6 });
        oranges.Add(new Orange() { Weight = 160, Measure = 6 });
        oranges.Add(new Orange() { Weight = 160, Measure = 6 });

        return oranges;
    }

And in my OrangeJuice class I have this method

public static int CreateJuice(List<Orange> oranges )
    {
        var bottle = new Bottle();
        var bottle2 = new Bottle();
        var cork = new Cork();
        var cork2 = new Cork();

        var orangeJuice = new OrangeJuice(1, 33, oranges, bottle, cork, 20);
        var orangeJuice2 = new OrangeJuice(2,33,oranges, bottle2,cork2, 20);

        var order = new Order();
        order.OrangeJuices.Add(orangeJuice);
        order.OrangeJuices.Add(orangeJuice2);

        var totalPrice = order.OrangeJuices.Sum(x => x.Price);

        return totalPrice;
    }

What I want to do to take the oranges I created on AddOrange method (six oranges) and put them in the CreateJuice method. So I get the list from the first method must somehow into the second method.

I'm wondering if I'm doing it correctly? And if not, how can I solve it?


回答1:


Normally the method called AddOrange should have been named as GetOranges

public static List<Orange> GetOranges()
{
    List<Orange> oranges = new List<Orange>();
    oranges.Add(new Orange() { Weight = 150, Measure = 6 });
    oranges.Add(new Orange() { Weight = 160, Measure = 6 });
    oranges.Add(new Orange() { Weight = 160, Measure = 6 });
    oranges.Add(new Orange() { Weight = 150, Measure = 6 });
    oranges.Add(new Orange() { Weight = 160, Measure = 6 });
    oranges.Add(new Orange() { Weight = 160, Measure = 6 });
    return oranges;
}

Then in the place you call the CreateJuice in you code, you only have to pass GetOranges.

CreateJuice(GetOranges());

or

var oranges = GetOranges();
var juice = CreateJuice(oranges);


来源:https://stackoverflow.com/questions/40875135/take-a-list-from-a-method-and-use-it-in-another-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!