如何在方法中使用List?

时间:2012-04-21 03:08:38

标签: .net list methods this

这是一个List<>这是在方法

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方法中使用flavor对象? 感谢。

2 个答案:

答案 0 :(得分: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();
  }
}

答案 1 :(得分: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();
    }
}

希望它有所帮助。

相关问题