0

私は3つのプロパティを持つクラス「製品」を持っています。ユーザーが 3 つのレコードを指定すると、それがリストに表示される単純なコンソール アプリケーションです。クラスの商品からリストを作成したのですが、なぜか無限エントリーになってしまいました!何が間違っているのかわからない

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 Yellow Bookを読むことをお勧めします。これは、初めて C# をプログラミングする方法を学ぶのに適した本です。

于 2013-08-15T09:45:41.800 に答える
0

Product のコンストラクターでは、新しい Product を作成しています。これにより、Product のコンストラクターが呼び出され、さらに別の Product が作成されます。つまり無限ループ!

于 2013-08-15T09:41:42.777 に答える