서비스 로직 분리 전 코드
< Form1.cs >
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO; // 파일스트림
namespace StudentApp
{
public partial class Form1 : Form
{
private List<Student> students = new List<Student>(); // 학생 리스트
public Form1()
{
InitializeComponent();
}
// [학생 생성 함수]
private void btnCreate_Click(object sender, EventArgs e)
{
string name = txtName.Text;
int age; // TryParse 라는 함수도 있음
try
{
age = int.Parse(txtAge.Text);
}
catch (FormatException)
{
MessageBox.Show("나이는 숫자로 입력해주세요.");
return;
}
string major = txtMajor.Text;
// 학생 객체 생성
Student student1 = new Student(name, age, major);
// 결과 출력
lbResult.Text = student1.Introduce();
// 학생 리스트에 추가
students.Add(student1);
listStudents.Items.Add(student1.Name);
}
// [ini 파일로 저장하는 함수]
private void btnSave_Click(object sender, EventArgs e)
{
try
{
StreamWriter writer = new StreamWriter("students.ini");
foreach (var student in students)
{
writer.WriteLine($"[{student.Name}]\nAge={student.Age}\nMajor={student.Major}\n");
}
writer.Close();
MessageBox.Show("저장 완료");
}
catch (Exception ex)
{
MessageBox.Show("파일 저장 실패");
}
}
// [리스트에서 학생 선택 시 상세 정보 출력] - 마우스로 더블클릭 했을 때
private void listStudents_MouseDoubleClick(object sender, MouseEventArgs e)
{
int index = listStudents.SelectedIndex; // 선택한 인덱스번호가 저장돼요
// SelectedIndex는 선택이 없을 때 -1을 반환하므로 예외처리 필요
if (index >= 0 && index < students.Count) // 인덱스 범위가 정상이라면
{
Student selectedStudent = students[index]; // 참조(포인터 같은 개념) - 쉽게 알아보기 위해서 사용
MessageBox.Show(selectedStudent.Introduce()); // 클래스의 메서드 호출
}
}
// [파일 불러오기 함수]
private void btnOpen_Click(object sender, EventArgs e)
{
try
{
// 파일 열기
StreamReader reader = new StreamReader("students.ini");
students?.Clear();
listStudents?.Items.Clear();
parseIniFile(reader); // 파싱 함수 호출!
reader.Close(); // 파일 닫기
MessageBox.Show("불러오기 완료");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
// [파싱하는 함수]
private void parseIniFile(StreamReader reader)
{
// 파싱값을 담을 변수들
string line;
string name = "";
int age = 0;
string major = "";
// ~반복문으로 한 줄씩 읽기~
while ((line = reader.ReadLine()) != null) // ReadLine이 EOF에 도달하면 null을 반환함
{
line = line.Trim(); // 공백 제거
if (string.IsNullOrWhiteSpace(line)) // 빈 줄이면 무시
{
continue;
}
// 대괄호 = 섹션 (파싱 시작)
if (line.StartsWith("[") && line.EndsWith("]")) // 1.이름
{
// 이름 변수가 비어있지 않으면 (비어있으면 조건문 통과)
if (!string.IsNullOrEmpty(name))
{
students.Add(new Student(name, age, major)); // 객체 생성!
listStudents.Items.Add(name);
}
// 새 학생 이름 초기화
name = line.Substring(1, (line.Length - 2)); // 여기서 이름을 담고 나가요 (나머지는 다음 조건문에서 담아요)
age = 0;
major = "";
// [이름]
// 이름에 대괄호 제거하고 저장 > 추출을 시작할 문자 위치, 끝나는 위치 (총 길이 -1은 대괄호)
// 이름이 3글자 이상일 수 있으니 길이로계산
}
// [나이]
else if (line.StartsWith("Age=")) // 2.나이
{
age = int.Parse(line.Substring(4)); // 4글자 이후부터 끝까지
}
// [전공]
else if (line.StartsWith("Major=")) // 3.전공
{
major = line.Substring(6); // 6글자 이후부터 끝까지
}
}
if (!string.IsNullOrEmpty(name)) // 이름이 비어있지 않다면
{
students.Add(new Student(name, age, major)); // 학생 리스트에 학생 추가 (일단 기본값으로 먼저 생성)
listStudents.Items.Add(name); // 리스트 박스에 이름 추가
}
}
private void btnClear_Click(object sender, EventArgs e)
{
txtName.Text = string.Empty;
txtAge.Text = string.Empty;
txtMajor.Text = string.Empty;
listStudents.Items.Clear();
}
}
}'C#' 카테고리의 다른 글
| static void Main(string[] args) 의 의미 (0) | 2025.11.04 |
|---|---|
| static이 아닌 필드, 메서드 또는 속성에 개체 참조가 필요합니다. (0) | 2025.11.04 |
| 학생 조회 프로그램 - 함수 설명 (기능명세서) (0) | 2025.11.04 |
| 학생 조회 프로그램 (0) | 2025.11.03 |
| 예외종류 :: 구체적인 예외로 어떤 오류인지 확인하기 (0) | 2025.11.03 |