2016-06-01 2 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

Ничего не получится, если я просто очищу свой код для вас. Вместо этого попробуйте это. Где бы вы ни находились, «Здесь я делаю бла». Это новая идея. Разбейте это на метод. и передать в используемые вами уроки и вернуть значение результата, которое будет использоваться. * Поместите статические объекты перед именами методов, потому что вы не создали экземпляр этого класса. – FirebladeDan

+0

Спасибо, Дэн, я определенно не просто хочу ответа. Я просто не знаю, с чего начать, я ценю помощь. – mattp341

ответ

0

Item Object - хранит экземпляр элемента (номер, описание)

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 - Обеспечивает чтение и запись статических методов ввода-вывода.

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

Смежные вопросы