0

我有具有三个属性的“产品”类。它是一个简单的控制台应用程序,用户在其中提供了三条记录并将其放入列表中。我从类产品创建列表,但由于某种原因它会无限进入!我不知道我做错了什么

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication5
{
  class Program
   {
    static void Main(string[] args)
    {
        Product obj1 = new Product();         
    }
  }

 class Product
 {     
    public int ID { get; set; }
    public string Name { get; set; }
    public string Price { get; set; }

    public Product()
    {
        Console.WriteLine("Enter Product Name: ");
        string name = Console.ReadLine();

        Console.WriteLine("Enter Product Price: ");
        string price = Console.ReadLine();

        List<Product> MyList = new List<Product>();

        MyList.Add(new Product() { ID = 1, Name = name, Price = price });

        foreach(var item in MyList)
        {
          Console.WriteLine("ID "+item.ID + " Name "+item.Name);

    }
 } //end product class
}
4

3 回答 3

2

在您的构造函数中,您创建一个新产品,这是您的循环

于 2013-08-15T09:39:17.417 回答
1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication5
{
   class Program
   {
      static void Main(string[] args)
         {
        List<Product> MyList = new List<Product>();

            Console.WriteLine("Enter Product Name: ");
            string name = Console.ReadLine(); 

            Console.WriteLine("Enter Product Price: ");
            string price = Console.ReadLine();

    MyList.Add(new Product{ ID = 1, Name = name, Price = price });

    foreach(var item in MyList)
            {
               Console.WriteLine("ID "+item.ID + " Name "+item.Name);
    }

    Console.WriteLine("End of Program; Press Enter to Exit");
    Console.ReadLine();
    }
}

public class Product
{     
   public int ID { get; set; }
   public string Name { get; set; }
   public string Price { get; set; }

   public Product()
   {   
   }
} //end product class
}

您通常在数据类中没有 UI 交互。

我可以建议您阅读Rob Miles 黄皮书,这是一本学习如何第一次编写 C# 的好书。

于 2013-08-15T09:45:41.800 回答
0

在 Product 的构造函数中,您正在创建一个新的 Product,它又会调用 Product 的构造函数,这将创建另一个 Product。换句话说,它是一个无限循环!

于 2013-08-15T09:41:42.777 回答