2013-08-15 3 views
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 
} 
+0

동일한 생성자에서 생성자를 호출하지 마십시오. 이 생성자에서 모두를 제거하고 이름과 가격을 취하는 초를 제공해야합니다. 그런 다음 이러한 인수를 사용하여 속성을 초기화 할 수 있습니다. –

+0

나는 constructor에서 콘솔을 읽는 것이 정말 나쁜 디자인이라고 생각한다. 처음에는 그런 물건을 본다. :) –

답변

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# 프로그래밍하는 방법을 배우기에 좋은 책입니다.

+0

예를 들어 세 개의 레코드가 필요하다. – toxic

+0

이것은 Program 클래스의 일부입니다. – ywm

2

잘못이 새 제품을 만드는 일을하고 모르는 차례로 호출에서, 제품 새 제품을 만드는에 대한 귀하의 생성자에서 루프

0

을하는 것이다 프로그래머 Product의 생성자는 또 다른 Product를 생성합니다. 즉, 무한 루프!

관련 문제