2016-06-01 6 views
-5

C#으로 기본 데이터 저장 프로그램을 만드는 중입니다. 나는 아주 새롭다, 나에 쉽게 가라. 나는 이것을 다른 클래스로 나눠서 다른 누군가가 자신의 메인 메소드에서 그것을 실행할 수 있도록하고 싶다. 내 문제는 어디에서 시작해야할지 모르겠다. 메서드에 대해 .cs 파일을 추가하려고 시도했지만 배열에 대한 참조와 같은 오류가 프로그램에 생성되었습니다. 여기에 내가 가진 것이있다.두 클래스로 프로그램 나누기

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

namespace Basic_Item_Entry 
{ 
    public class Program 
    { 
     static void Main(string[] args) 
     { 
      Console.WriteLine("This program is designed to take input and hold   data for 10 items"); 
      //make array for item #'s and add 10 values 
      Console.WriteLine("Enter 10 item numbers"); 
      int[] itemNums = new int[10]; 
      for(int i = 0; i <itemNums.Length; i++) 
      { 

       itemNums[i] = Convert.ToInt32(Console.ReadLine()); 

      } 
      //make array for item descriptions 
      string[] itemDesc = new string[10]; 
      for(int i = 0; i < itemNums.Length; i++) 
      { 
       Console.WriteLine("Enter the description for item number: " +  itemNums[i]); 
       itemDesc[i] = Console.ReadLine(); 
      } 
      //add contents of arrays to a file @"C:\temp\DataEntry.txt" 
      using (System.IO.StreamWriter file = new System.IO.StreamWriter(
       @"C:\temp\DataEntry.txt")) 
      { 
       file.WriteLine("Item Data:"); 
       for (int i = 0; i < itemNums.Length; i++) 
       { 
        file.WriteLine("Item number " + itemNums[i] + " Description: " + itemDesc[i]); 

       } 
       file.Close(); 
      } 
      //finish and maybe print contents from file 
      Console.WriteLine("Data has been recorded to a file. Would you like      to view the the contents? y/n"); 
      //print array data from previously written to file     @"C:\temp\DataEntry.txt" 
      try 
      { 
       if (Console.ReadLine().Equals("y")) 
       { 
        using (StreamReader stringRead = new  StreamReader(@"C:\temp\DataEntry.txt")) 
        { 
         String DataEntryTXT = stringRead.ReadToEnd(); 
         Console.WriteLine(DataEntryTXT); 

        } 
       } 
       //dont print anything, just exit (Still creates the file) 
       else 
       { 
        System.Environment.Exit(1); 
       } 

      } 
      catch(Exception ex) 
      { 
       Console.WriteLine("File not found"); 
       Console.WriteLine(ex.Message); 
      } 


      Console.ReadLine(); 
     } 
    } 
} 
+0

에 그것을 읽을 수있는 설명 논리를 포함합니다. 몇 분만 줘. –

+1

방금 ​​코드를 정리하면 아무 것도 얻지 못할 것입니다. 대신 이것을 시도하십시오. 어디에서든지 "나는 여기있다"라고 생각하면 새로운 생각입니다. 그것을 방법으로 분해하십시오. 사용중인 vars를 전달하고 사용할 결과 값을 반환합니다. *이 클래스의 인스턴스를 만들지 않았기 때문에 메서드 이름 앞에 static을 추가합니다. – FirebladeDan

+0

Dan, 고맙습니다. 답을 원합니다. 어디서부터 시작해야할지 모르겠다. 도움을 청한다. – mattp341

답변

0

항목 개체 - 항목의 인스턴스 (번호, 설명)

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

namespace BasicDataStorageApp 
{ 
    public class Item 
    { 
     private int _number; 

     public int Number 
     { 
      get { return _number; } 
      set { _number = value; } 
     } 

     private string _description; 

     public string Description 
     { 
      get { return _description; } 
      set { _description = value; } 
     } 

     public Item(int number, string description) 
      : this() 
     { 
      _number = number; 
      _description = description; 
     } 

     public Item() 
     { 
     } 

     public override string ToString() 
     { 
      return string.Format("Item number {0} Description {1}", _number, _description); 
     } 
    } 
} 

모델 개체를 저장합니다 - 항목의 컬렉션을 저장하고 읽거나 파일에 기록하는 방법이 포함되어 있습니다.

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

namespace BasicDataStorageApp 
{ 
    public class Model 
    { 
     private Item[] _items; 

     public Item[] Items 
     { 
      get { return _items; } 
      set { _items = value; } 
     } 

     public bool WriteItems(string filename, bool append) 
     { 
      if (_items != null) 
      { 
       for (int i = 0; i < _items.Length; i++) 
       { 
        string str = _items[i].ToString(); 
        FileHelper.WriteLine(str, filename, append); 
       } 

       return true; 
      } 

      return false; 
     } 

     public IEnumerable<string> ReadItems(string filename) 
     { 
      return FileHelper.ReadLines(filename); 
     } 
    } 
} 

FileHelper - 읽기 및 쓰기 IO 정적 메서드를 제공합니다.

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

namespace BasicDataStorageApp 
{ 
    public static class FileHelper 
    { 
     public static bool WriteLines(IEnumerable<string> lines, string filename, bool append) 
     { 
      try 
      { 
       using (StreamWriter writer = new StreamWriter(filename, append)) 
       { 
        foreach (var line in lines) 
        { 
         writer.WriteLine(line); 
        } 
       } 

       return true; 
      } 
      catch (Exception ex) 
      { 
       throw ex; 
      } 
     } 

     public static bool WriteLine(string line, string filename, bool append) 
     { 
      try 
      { 
       using (StreamWriter writer = new StreamWriter(filename, append)) 
       { 
        writer.WriteLine(line); 
       } 

       return true; 
      } 
      catch (Exception ex) 
      { 
       throw ex; 
      } 
     } 

     public static IEnumerable<string> ReadLines(string filename) 
     { 
      try 
      { 
       var lines = new List<string>(); 

       using (StreamReader reader = new StreamReader(filename)) 
       { 
        string line = null; 
        while ((line = reader.ReadLine()) != null) 
        { 
         lines.Add(line); 
        } 
       } 

       return lines; 
      } 
      catch (Exception ex) 
      { 
       throw ex; 
      } 
     } 
    } 
} 

프로그램 - 사용자 입력을받을 파일에 기록하고 제가 무엇을 할 수 있는지 보자 다시 사용자

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

namespace BasicDataStorageApp 
{ 
    class Program 
    { 
     static Model _model; 
     const int _totalInput = 10; 
     const string _filename = @"C:\temp\DataEntry.txt"; 

     static void Main(string[] args) 
     { 
      _model = new Model(); 
      _model.Items = new Item[_totalInput]; 

      Console.WriteLine("This program is designed to take input and hold data for 10 items"); 

      int i = 0; 
      while (i < _totalInput) 
      { 
       int number = -1; 

       Console.WriteLine("\nEnter number: "); 
       string numberValue = Console.ReadLine(); 

       if (Int32.TryParse(numberValue, out number)) 
       { 
        _model.Items[i] = new Item(number, null); 

        Console.WriteLine("\nEnter description: "); 
        string descriptionValue = Console.ReadLine(); 

        _model.Items[i].Description = descriptionValue; 

        i++; 
       } 
      } 

      _model.WriteItems(_filename, true); 

      var itemStrings = _model.ReadItems(_filename); 
      foreach (var s in itemStrings) 
      { 
       Console.WriteLine(s); 
      } 

      Console.ReadLine(); 
     } 
    } 
} 
+0

이것은 아주 좋습니다. 시간 내 주셔서 감사합니다! – mattp341

관련 문제