2012-04-21 30 views
0

下面列出了<>这是一个方法如何在方法中使用列表?

public void MenuList() 
{ 
    List<string> flavors = new List<string>(); 
    flavors.Add("Angus Steakhouse"); 
    flavors.Add("Belly Buster"); 
    flavors.Add("Pizza Bianca"); 
} 

里面现在,我把一个新的方法

public int GetSizePrices(int num) 
{ 
    this.MenuList ???  
} 

如何使用内部GetSizePrices方法的味道对象? 谢谢。

+0

你想让GetSizePrices()方法对flavors对象做什么? – 2012-04-21 03:16:44

+0

只需在GetSizePrices()方法内读取并使用它即可。我想第一个答案是我正在寻找的。 – Ryan 2012-04-21 03:28:57

+0

更重要的问题是,口味是否应该改变?或者,MenuList()方法是否应该专门负责创建并向其他所有方法传递该列表?最具体地说,您是否可以更新您的问题以显示您实际正在尝试执行的操作? – 2012-04-21 03:31:49

回答

0

我认为你正在寻找的东西一样?:

public Class SomeClass 
{ 
    public IEnumerable<string> MenuList() 
    { 
    List<string> flavors = new List<string>(); 
    flavors.Add("Angus Steakhouse"); 
    flavors.Add("Belly Buster"); 
    flavors.Add("Pizza Bianca"); 
    return flavors; 
    } 

    public int GetSizePrices(int num) 
    { 
    // No idea what to do with num 
    return this.MenuList().Count(); 
    } 
} 
+0

-1 OP对于C#来说显然是新的,这并不解释如何将'flavors'放入字段(或属性)中,然后可以在同一个类中使用其他方法。 – 2012-04-21 03:12:19

+0

我同意你的断言,它没有解释它是如何做的,但我也认为OP的问题是不明确的,这个答案在一般水平上确实可以访问flavor对象。 – 2012-04-21 03:16:03

0

显然有许多不同的方式来实现这一点,将根据您的设计要求。

现在让我们假设你是C#的新手,你可以考虑这两个简单的方法让你开始你的旅程(我有意地忽略了惯用的C#以尽可能熟悉你现有的代码)。


选项1 - 把它作为参数:

public List<string> BuildMenuList() 
{ 
    List<string> flavors = new List<string>(); 
    flavors.Add("Angus Steakhouse"); 
    flavors.Add("Belly Buster"); 
    flavors.Add("Pizza Bianca"); 

    return flavors; 
} 

public int GetSizePrices(int num, List<string> menuList) 
{ 
    // access to menuList 
    var cnt = menuList.Count(); 
} 


选择2 - 让它可以作为财产

public class Menu 
{ 
    // A public property that is accessible in this class and from the outside 
    public List<string> MenuList { get; set;} 

    public Menu() 
    { 
     // Populate the property in the constructor of the class 
     MenuList = new List<string>(); 
     MenuList.Add("Angus Steakhouse"); 
     MenuList.Add("Belly Buster"); 
     MenuList.Add("Pizza Bianca"); 
    } 

    public int GetSizePrices(int num) 
    { 
     // your implementation details here... 
     return MenuList.Count(); 
    } 
} 

希望它能帮助。

相关问题