Using과 Try-Finally 비교
Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨. 66개 중 28번째.
using 문과 try-finally 블록은 모두 적절하게 삭제되어야 하는 리소스를 관리하는 데 도움이 됩니다. using 문은 IDisposable 객체가 적절하게 정리되도록 보장하는 더 깔끔하고 간결한 방법을 제공합니다.
참고: using은 리소스 해제를 위한 try-finally 패턴을 대체합니다. try-catch를 대체하는 것은 아닙니다. 예외를 처리하기 위해 using 블록을 try-catch 안에 작성할 수 있습니다.
먼저 try-finally 접근 방식을 살펴보겠습니다.
StreamReader reader = null;
try
{
reader = new StreamReader("file.txt");
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
finally
{
if (reader != null)
{
reader.Dispose();
}
}
using 문은 이 코드를 간소화합니다:
using (StreamReader reader = new StreamReader("file.txt"))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
using 문은 블록이 종료될 때 예외가 발생하더라도 자동으로 Dispose()를 호출합니다.
StreamReader란 무엇인가요?StreamReader는 파일에서 텍스트를 읽는 데 사용되는 클래스입니다. filename을 전달하여 생성하면 읽기를 위해 file을 엽니다. IDisposable을 구현하므로 사용 후 올바르게 닫아야 하며, 바로 이 작업을 using이 대신 처리합니다.
일반적인 StreamReader 메서드:
ReadToEnd(): 파일 전체를 하나의 문자열로 읽습니다ReadLine(): 한 번에 한 줄씩 읽으며, 파일 끝에 도달하면null을 반환합니다
파일의 줄 수를 세려면 ReadLine() 루프를 사용할 수 있습니다:
using (StreamReader reader = new StreamReader("file.txt"))
{
int lineCount = 0;
while (reader.ReadLine() != null)
{
lineCount++;
}
Console.WriteLine(lineCount);
}
using을 try-catch와 함께 사용하여 파일 누락과 같은 예외를 처리할 수도 있습니다:
try
{
using (StreamReader reader = new StreamReader("file.txt"))
{
int lineCount = 0;
while (reader.ReadLine() != null)
{
lineCount++;
}
Console.WriteLine(lineCount);
}
}
catch (FileNotFoundException)
{
Console.WriteLine("File not found");
}
챌린지
쉬움processFile이라는 이름의 메서드를 작성하세요. 이 메서드는 다음을 수행해야 합니다:
string매개변수로 filename을 받습니다StreamReader와 함께using문을 사용하여 파일에서 모든 줄을 읽습니다- 파일의 줄 수를 반환합니다
FileNotFoundException이 발생하면 "File not found"를 출력하고 -1을 반환합니다
직접 해보기
using System;
using System.IO;
class ProcessFile
{
public static int processFile(string filename)
{
// 여기에 코드를 작성하세요
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리 및 흐름의 모든 레슨
직접 연습해 보세요: 온라인 C# 컴파일러