提问者:小点点

如何从字典访问其他方法?


如何从一种方法访问另一种方法?下面是AddProduct()方法中的Dictionary Products,它包含一些数据,稍后将添加一些新数据。方法CheckProcutList()显示所有产品,以及添加到字典中的内容。用一种方法检查产品清单是没有问题的,但它是如何单独制作的呢?换句话说,如何使产品全球化?

       public static void AddProduct()
        {
            var Products = new Dictionary<string, decimal>()
            {
                {"Apple Juice", 2.5M},
                {"Pizza", 16.7M},
                {"Cheese Cake", 4.5M},
            };

        }
        public static void CheckProcutList()
        {
            foreach (var kvp in Products) //Here is a problem
                Console.WriteLine("Product name: {0}, Price: {1}", kvp.Key, kvp.Value);

            SwitchMenu();
        }

共1个答案

匿名用户

将产品移到addProducts方法之外,并使其保持静态。

        public static Dictionary<string, decimal> Products;
        public static void AddProduct()
        {
            Products = new Dictionary<string, decimal>()
           {
              {"Apple Juice", 2.5M},
              {"Pizza", 16.7M},
              {"Cheese Cake", 4.5M},
           };

        }
        public static void CheckProcutList()
        {
            foreach (var kvp in Products) //Here is a problem
                Console.WriteLine("Product name: {0}, Price: {1}", kvp.Key, kvp.Value);

            SwitchMenu();
        }