有一本字典,里面已經包含了一些資料。如何將新資料添加到已存在的資料?并且所有方法都必須由我單獨制作,因為我將在 switch 中呼叫它們。
public class Product
{
public static Dictionary<string, decimal> ProductStore()
{
return new Dictionary<string, decimal>()
{
{ "Apple Juice", 2.5M },
{ "Pizza", 16.7M },
{ "Cheese Cake", 4.5M },
};
}
public static void CheckProductList()
{
foreach (var kvp in ProductStore())
Console.WriteLine("Product name: {0}, Price: {1}", kvp.Key, kvp.Value);
}
public static void AddProduct()
{
string ProductName = Console.ReadLine();
decimal ProductPrice = decimal.Parse(Console.ReadLine());
ProductStore()[ProductName] = ProductPrice;
}
}
問題是,新字典總是回傳一些資料?
uj5u.com熱心網友回復:
您應該保留您的字典并僅將其實體化一次。例如,可以使用私有支持欄位。同樣在添加資料時,您應該檢查具有給定鍵的資料是否存在,然后您應該更新該值。
public static class Product
{
private static readonly Dictionary<string, decimal> ProductStore = new Dictionary<string, decimal>()
{
{ "Apple Juice", 2.5M },
{ "Pizza", 16.7M },
{ "Cheese Cake", 4.5M },
};
public static Dictionary<string, decimal> GetProductStore()
{
return ProductStore;
}
public static void CheckProductList()
{
foreach (var kvp in ProductStore)
Console.WriteLine("Product name: {0}, Price: {1}", kvp.Key, kvp.Value);
}
public static void AddProduct()
{
string ProductName = Console.ReadLine();
decimal ProductPrice = decimal.Parse(Console.ReadLine());
if (!ProductStore.TryAdd(ProductName, ProductPrice))
ProductStore[ProductName] = ProductPrice;
}
}
uj5u.com熱心網友回復:
我認為您想要的只是使 Dictionary 成為一個欄位/屬性(而不是每次都創建它)。這樣就記住了這些值。
using System;
using System.Collections.Generic;
public class ProductRepository
{
private readonly Dictionary<string, decimal> _products;
public ProductRepository()
{
_products = new Dictionary<string, decimal>()
{
{ "Apple Juice", 2.5M },
{ "Pizza", 16.7M },
{ "Cheese Cake", 4.5M },
};
}
public IReadOnlyDictionary<string, decimal> Products => _products;
public void AddOrUpdateProduct(string productName, decimal price)
{
_products[productName] = price;
}
}
public static class Program
{
public static void Main()
{
var productRepository = new ProductRepository();
PrintAllProducts(productRepository);
Console.WriteLine("Now add a new product by giving the name and price.");
var newProductName = Console.ReadLine();
var newProductPrice = decimal.Parse(Console.ReadLine());
productRepository.AddOrUpdateProduct(newProductName, newProductPrice);
PrintAllProducts(productRepository);
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
}
private static void PrintAllProducts(ProductRepository productRepository)
{
foreach (var (productName, price) in productRepository.Products)
{
Console.WriteLine($"Product {productName} costs {price}.");
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/388625.html
標籤:C#
