我如何使用 ConsoleReadKey 解决问题

问题描述 投票:0回答:0

任何人都可以帮我解决与

Console.Readkey
相关的问题吗?
这是我的代码:

public class AddProduct
{
    Dictionary<string, Product> products = new Dictionary<string, Product>();

    public AddProduct()
    {
        this.products = products;
    }

    public void AddProductsToDictionary()
    {
        Console.WriteLine("Please enter your products:");
        int total = 0;
        Guid guid = Guid.NewGuid();
        
        while (Console.ReadKey().Key != ConsoleKey.Escape)
        {
            string productName = Console.ReadLine();
            string uniqCode = guid.ToString();
            Product product = new Product()
            {
                Quantity = total,
                Code = uniqCode
            };
            products.Add(productName, product);
        }
        
        ShowProducts();
    }

    private void ShowProducts()
    {
        Console.WriteLine("List of products:");
        foreach (var product in products)
        {
            Console.WriteLine("Name: {0}, ProductCode: {1}", product.Key, product.Value.Code);
        }
    }

现在

Console.Readkey().Key
括号中没有
true
,最后当我想显示结果时,我没有从控制台写入行和产品中得到所有字母,例如我得到的不是“产品列表” “产品列表”或代替“名称”我得到“我”。

但如果我把

true
放在括号中,它们就会正确显示,因为使用控制台,我必须按两次 enter 才能输入产品,而我只想按一次 enter。

谁能帮我解决这个问题?

我试图理解为什么

Console.Readkey
不起作用以及为什么它吃字母。

c# console
© www.soinside.com 2019 - 2024. All rights reserved.