UsingとTry-Finallyの比較
CoddyのC#ジャーニー「ロジックとフロー」セクションの一部。レッスン 28/66。
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は、fileからtextを読み取るために使用されるclassです。filenameを渡して作成すると、読み取り用にfileを開きます。IDisposableを実装しているため、使用後は適切に閉じる必要がありますが、usingがまさにその処理を行ってくれます。
一般的なStreamReaderメソッド:
ReadToEnd():ファイル全体を1つの文字列として読み取りますReadLine():1行ずつ読み取り、ファイルの末尾に到達すると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#オンラインコンパイラ