从方法中获取列表并在另一种方法中使用它

时间:2016-11-29 20:23:37

标签: c# methods parameters

在我的Orange课程中,我有这种方法:

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

在我的OrangeJuice课程中,我有这种方法

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

我想在AddOrange方法(六个橙子)上创建橙子并将它们放入CreateJuice方法中。所以我从第一种方法得到的列表必须以某种方式进入第二种方法。

我想知道我是否正确地做到了?如果没有,我该如何解决?

1 个答案:

答案 0 :(得分:2)

通常,名为AddOrange的方法应该被命名为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;
}

然后,在您在代码中调用CreateJuice的地方,您只需要传递GetOranges

CreateJuice(GetOranges());

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