2016-11-29 49 views
-1

在我的橙類我有這樣的方法:從方法採取列表,並使用它的另一種方法

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

你做正確! oragnes是您在CreateJuice中的桔子列表 –

+0

您在哪裏調用第一種方法?它看起來像第一個方法返回一個橙子列表,第二個方法接受一個橙子列表。所以無論調用這些方法的代碼都可以處理。 – David

+1

var myJuice = CreateJuice(AddOrange()); – slugster

回答

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); 
相關問題