이 오류는 인스턴스 멤버(non-static member)를 인스턴스(객체) 없이 직접 호출하려고 할 때 발생
Non-static (인스턴스) 메서드/필드:
특정 객체 인스턴스에 속하며, 해당 객체의 데이터를 사용하여 작동합니다.
사용하기 전에 반드시 클래스의 인스턴스를 생성해야 합니다.
Static (정적) 메서드/필드:
클래스 자체에 속하며, 객체 생성 없이 클래스 이름으로 직접 호출할 수 있습니다.
정적 메서드는 인스턴스 데이터를 참조할 수 없습니다.
>> 메서드가 static으로 선언되지 않았기 때문에
컴파일러는 이 메서드를 호출할 때 어떤 특정 writeFile 객체에 대해 실행해야 할지 알 수 없어 오류를 발생
< writeFile.cs >
namespace StudentApp
{
internal class writeFile
{
public void writeFile_(List<Student> students)
{
try
{
StreamWriter writer = new StreamWriter("students.ini");
foreach (var student in students)
{
writer.WriteLine($"Name={student.Name};Age={student.Age};Major={student.Major}");
}
writer.Close();
MessageBox.Show("학생 정보가 저장되었습니다.");
}
catch (Exception ex)
{
MessageBox.Show($"파일 저장 중 오류가 발생했습니다: {ex.Message}");
}
}
}
}
< Form1.cs >
private void btnSave_Click(object sender, EventArgs e)
{
writeFile writeFile = new writeFile(); // writeFile 클래스의 객체 생성
writeFile.writeFile_(students);
}
>> writeFile.cs 클래스는 그저 모양틀이기 때문에 현재 실체가 없다.
따라서 Form1.cs 에서 writeFile_ 메서드를 사용하려면 writeFile 클래스로 생성한 객체가 필요하다.
하지만!
readFile과 writeFile을 클래스로 각각 나누기에는 오래 걸린다.
어쨌든 둘다 File 이라는 명사를 공통적으로 공유하고 있으니 iniFile 이라는 클래스를 만들어서
read 메서드와 write 메서드를 만드는 것이 좋겠다.
'C#' 카테고리의 다른 글
| 필드(전역)변수와 내부(지역)변수 (0) | 2025.11.04 |
|---|---|
| static void Main(string[] args) 의 의미 (0) | 2025.11.04 |
| 학생 조회 프로그램 - origin 코드 (0) | 2025.11.04 |
| 학생 조회 프로그램 - 함수 설명 (기능명세서) (0) | 2025.11.04 |
| 학생 조회 프로그램 (0) | 2025.11.03 |