首页 > 解决方案 > 我想在 C# 中使用对象数组显示一些产品

问题描述

我有一堂课

public class Product
{
    private long id;   
    private String name;  
    private String internCode;  
    private String producer;// 

    public long Id { get => id; set => id = value; }
    public string Name { get => name; set => name = value; }
    public string InternCode { get => internCode; set => internCode = value; }
    public string Producer { get => producer; set => producer = value; }

    public void display()
    {
        Console.WriteLine("Products: " +Id+"  "+Name + "[" +InternCode + "] " + Producer);
    }
}

这是程序类

 public static void Main(string[] args)
    {
        Product prod1 = new Product();
        Product prod2 = new Product();
        Console.WriteLine("The Id for the first product is:");
        prod1.Id = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("The name of the first product is:");
        prod1.Name = Console.ReadLine();
        Console.WriteLine("The Intern Code is:");
        prod1.InternCode = Console.ReadLine();
        Console.WriteLine("The producer is:");
        prod1.Producer = Console.ReadLine();

        Console.WriteLine();
        Console.WriteLine("The Id for the second product is:");
        prod2.Id = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("The name for the second product is:");
        prod2.Name = Console.ReadLine();
        while (prod2.Name == prod1.Name)
        {
            Console.WriteLine("This product has already been introduced. Please introduce a new product:");
            prod2.Name = Console.ReadLine();
        }
        Console.WriteLine("The intern code is:");
        prod2.InternCode = Console.ReadLine();
        Console.WriteLine("The producer is:");
        prod2.Producer = Console.ReadLine();


        Console.WriteLine("The products are:");
        Console.WriteLine();
        prod1.display();
        Console.WriteLine();
        prod2.display();
        Console.WriteLine();
        Console.ReadKey();            
    }

我想通过用户输入读取产品并使用对象数组 Product[] array1=new Product[] 显示它们,而不是使用 prod1 和 prod2 对象。请给我任何示例或任何链接来记录我如何解决这个问题。谢谢!

标签: c#arrayobject

解决方案


我建议您使用 List,因为您有 Add 方法来添加新产品。要检查产品是否存在,您可以使用 Linq 的 IEnumerable 的 Any 扩展:

var products = new List<Product>();
...
while (!lastuserinput.Equals("exit"))
{    
    var productName = Console.ReadLine(); 
    if (products.Any(product=>product.Name.Equals(productName))
    {
       Console.WriteLine("product already exists");
       continue;
    }
    ...
    productList.Add(new Product
    {
        ...
        Name = productName,
        ...
    };
...
}

推荐阅读