



public enum Gender { 남성 = 1, 여성 = 2 }
class Student
{
public string Name { get; set; }
public Gender StudentGender { get; set; }
public int Score { get; set; }
public override string ToString() //Tostring 메서드를 재정의해서 원하는 형태로 사용
{
return $"{Name}[{StudentGender}][{Score}]";
}
}
-------------------------------------------------------------------------------------------------------
class Class1
{
Student[] students = new Student[3];
public void Run()
{
ReadStudents();
PrintStudents();
}
private void PrintStudents()
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine(students[i]);
// 기본적으로 Object 를 출력 시 toString 메서드가 호출됨
// toString 메서드는 기본적으로 클래스의 이름(네임스페이스 포함) 을 출력한다.
// toString 재정의 후 사용
}
}
private void ReadStudents()
{
FileStream stream = new FileStream(@"D:\Student.txt", FileMode.Open);
StreamReader reader = new StreamReader(stream, UTF8Encoding.UTF8);
string buffer = null;
int index = 0;
while((buffer = reader.ReadLine()) != null) // 읽을 내용이 있으면 반복
{
InsertStudent(buffer, index++);
}
}
private void InsertStudent(string buffer, int index)
{
Student st = new Student();
string[] tmp = buffer.Split('#'); // temp[0], temp[1], temp[2]
if(tmp.Length != 3)
{
throw new Exception("텍스트 내용에 오류가 있습니다 : " + buffer);
}
st.Name = tmp[0];
st.Score = int.Parse(tmp[2]);
int isGen = int.Parse(tmp[1]);
st.StudentGender = (Gender)Enum.ToObject(typeof(Gender), isGen); // int 값을 Enum 을 바꿔주는 과정
students[index] = st;
}
}
Student.txt
홍길동#1#87
장길산#1#56
황진이#2#78
출력 결과
홍길동[남성][87]
장길산[남성][56]
황진이[여성][78]
- D:\Student.txt 파일에 저장된 값을 더 이상 읽을 내용이 없을 때 까지 읽음
- #을 기준으로 Student 파일에 값을 분리하여 Student 객체에 입력
- 재정의한 toString 메서드를 사용해서 학생의 정보 출력
변수를 선언할 때 초기 값을 선언하지 않을 경우 원치 않는 값이 저장되는 경우가 있음
class Class1
{
public void Run()
{
Member m = new Member();
Console.WriteLine(m.GetMarried);
}
}
class Member
{
Console.WriteLine(m.GetMarried ? "기혼" : "미혼");
}
출력결과 : 미혼 -> 원하지 않는 초기값이 설정됨
class Class1
{
public void Run()
{
Member m = new Member();
if (m.GetMarried.HasValue) // getMarried 가 값이 있으면 -> null 이 아니면
{
Console.WriteLine(m.GetMarried == true ? "기혼" : "미혼");
// Nullable로 선언 시 == 붙어야함
}
else
{
Console.WriteLine("정보 없음");
}
}
}
class Member
{
public Nullable<bool> GetMarried { get; set; }
// public bool? GetMarried { get; set; } 이렇게도 사용 가능
}
null이 아니면 값을 반환하고 null이면 지정한 값 반환
string name = null;
Console.WriteLine(name ?? "이름없음");
// name 있으면 name, 없으면 "이름없음" 출력