.NETヘルプ C# Using (開発者向けの仕組み) Curtis Chau 更新日:6月 22, 2025 Download IronPDF NuGet Download テキストの検索と置換 テキストと画像のスタンプ Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article たとえ C#の基本を学び始めたばかりだとしても、using ディレクティブにすでに出会っている可能性があります。そして、IronPDF ユーザーであれば、using ironpdfという名前空間でコードを開始することに非常に慣れているでしょう。 しかし、using キーワードにはもう一つの用途があります。 このガイドでは、using ステートメントとは何か、それがどのように機能するのか、そしてそれがどのようにしてより効率的なコードを作成するのに役立つかを見ていきます。 さあ始めましょう! C#のUsingとは何か? C#のusingステートメントは、IDisposableインターフェイスを実装するリソースを扱うための便利な方法です。 IDisposableオブジェクトは通常、ファイルハンドルやネットワーク接続のようなアンマネージリソースを保持し、使用後に解放する必要があります。 これがusingステートメントが役立つところで、リソースが利用後に適切に解放されることを保証します。 Usingステートメントの仕組み using ステートメントを使うと、C# はそのオブジェクトが不要になると自動的に Dispose メソッドを呼び出します。 これにより、Dispose メソッドを手動で呼び出す必要がなくなり、呼び忘れる心配もありません。 using ステートメントがそれを処理してくれます! usingステートメントがどのように機能するかを見るための簡単な例を見てみましょう: using System; using System.IO; class Program { static void Main() { // Using a using statement to ensure StreamReader is disposed of using (StreamReader reader = new StreamReader("example.txt")) { string content = reader.ReadToEnd(); Console.WriteLine(content); } } } using System; using System.IO; class Program { static void Main() { // Using a using statement to ensure StreamReader is disposed of using (StreamReader reader = new StreamReader("example.txt")) { string content = reader.ReadToEnd(); Console.WriteLine(content); } } } Imports System Imports System.IO Friend Class Program Shared Sub Main() ' Using a using statement to ensure StreamReader is disposed of Using reader As New StreamReader("example.txt") Dim content As String = reader.ReadToEnd() Console.WriteLine(content) End Using End Sub End Class $vbLabelText $csharpLabel この例では、reader という名前の StreamReader オブジェクトが using ブロックでラップされています。 using ブロックを抜けると、Dispose メソッドが自動的に reader に対して呼び出され、保持していたリソースが解放されます。 Using ブロック対Using 宣言 C# 8.0 からは、using ブロックの代わりに using 宣言を使用できます。 using 宣言は、次のようにディスポーザブルオブジェクトを定義するための短く簡潔な方法です: using System; using System.IO; class Program { static void Main() { // Using the using declaration simplifies the code using var reader = new StreamReader("example.txt"); string content = reader.ReadToEnd(); Console.WriteLine(content); } } using System; using System.IO; class Program { static void Main() { // Using the using declaration simplifies the code using var reader = new StreamReader("example.txt"); string content = reader.ReadToEnd(); Console.WriteLine(content); } } Imports System Imports System.IO Friend Class Program Shared Sub Main() ' Using the using declaration simplifies the code Dim reader = New StreamReader("example.txt") Dim content As String = reader.ReadToEnd() Console.WriteLine(content) End Sub End Class $vbLabelText $csharpLabel using 宣言では、中括弧やインデントが不要になり、コードがより読みやすくなります。 変数がスコープから外れたときに、Dispose メソッドが自動的に呼ばれます。 Try ブロック、Finally ブロック、およびUsing ステートメント using ステートメントが C# の try と finally ブロックとどう関連しているのか不思議に思うかもしれません。 実際、using ステートメントは try-finally ブロックの短縮形です! 前回と同じ例を using ステートメントの代わりに try-finally ブロックを使って書いたものです: using System; using System.IO; class Program { static void Main() { StreamReader reader = null; try { reader = new StreamReader("example.txt"); string content = reader.ReadToEnd(); Console.WriteLine(content); } finally\static-assets\pdf\blog\csharp-using\csharp-using-2.webp { if (reader != null) { reader.Dispose(); } } } } using System; using System.IO; class Program { static void Main() { StreamReader reader = null; try { reader = new StreamReader("example.txt"); string content = reader.ReadToEnd(); Console.WriteLine(content); } finally\static-assets\pdf\blog\csharp-using\csharp-using-2.webp { if (reader != null) { reader.Dispose(); } } } } Imports System Imports System.IO Friend Class Program Shared Sub Main() Dim reader As StreamReader = Nothing Try reader = New StreamReader("example.txt") Dim content As String = reader.ReadToEnd() Console.WriteLine(content) Finally \static-assets\pdf\blog\csharp-using\csharp-using-2.webp If reader IsNot Nothing Then reader.Dispose() End If End Try End Sub End Class $vbLabelText $csharpLabel ご覧のとおり、using ステートメントは try-finally ブロックと Dispose メソッドを明示的に呼び出す必要をなくし、コードをよりクリーンで読みやすくします。 複数のリソースの管理 using ステートメントの素晴らしい点の一つは、複数のリソースを同時に扱えることです。 using ステートメントを次々に重ねたり、カンマで区切ったリストで複数のリソースを扱う単一の using ステートメントを使用することができます。以下にその両アプローチを示した例があります: using System; using System.IO; class Program { static void Main() { // Stacking using statements for multiple disposable resources using (StreamReader reader1 = new StreamReader("example1.txt")) using (StreamReader reader2 = new StreamReader("example2.txt")) { string content1 = reader1.ReadToEnd(); string content2 = reader2.ReadToEnd(); Console.WriteLine($"Content from example1.txt:\n{content1}\nContent from example2.txt:\n{content2}"); } // Attempting to use a single using statement with multiple resources (not valid) // Note: This method using comma-separated resources is not supported in C# } } using System; using System.IO; class Program { static void Main() { // Stacking using statements for multiple disposable resources using (StreamReader reader1 = new StreamReader("example1.txt")) using (StreamReader reader2 = new StreamReader("example2.txt")) { string content1 = reader1.ReadToEnd(); string content2 = reader2.ReadToEnd(); Console.WriteLine($"Content from example1.txt:\n{content1}\nContent from example2.txt:\n{content2}"); } // Attempting to use a single using statement with multiple resources (not valid) // Note: This method using comma-separated resources is not supported in C# } } Imports Microsoft.VisualBasic Imports System Imports System.IO Friend Class Program Shared Sub Main() ' Stacking using statements for multiple disposable resources Using reader1 As New StreamReader("example1.txt") Using reader2 As New StreamReader("example2.txt") Dim content1 As String = reader1.ReadToEnd() Dim content2 As String = reader2.ReadToEnd() Console.WriteLine($"Content from example1.txt:" & vbLf & "{content1}" & vbLf & "Content from example2.txt:" & vbLf & "{content2}") End Using End Using ' Attempting to use a single using statement with multiple resources (not valid) ' Note: This method using comma-separated resources is not supported in C# End Sub End Class $vbLabelText $csharpLabel 注意:C# は複数のリソースをカンマで区切った単一の using ステートメントをサポートしていません。 各リソースには独自の using ステートメントが必要です。 IDisposable インターフェイスの実装 時には、1つ以上のリソースを管理する独自のカスタムクラスを作成することもあるかもしれません。 クラスがディスポーザブルオブジェクトやアンマネージリソースを扱う責任を持つ場合、IDisposable インターフェイスを実装するべきです。 以下に IDisposable インターフェイスを実装したカスタムクラスの例を示します: using System; using System.IO; public class CustomResource : IDisposable { private StreamReader _reader; public CustomResource(string filePath) { _reader = new StreamReader(filePath); } public void ReadContent() { string content = _reader.ReadToEnd(); Console.WriteLine(content); } public void Dispose() { if (_reader != null) { _reader.Dispose(); _reader = null; } } } using System; using System.IO; public class CustomResource : IDisposable { private StreamReader _reader; public CustomResource(string filePath) { _reader = new StreamReader(filePath); } public void ReadContent() { string content = _reader.ReadToEnd(); Console.WriteLine(content); } public void Dispose() { if (_reader != null) { _reader.Dispose(); _reader = null; } } } Imports System Imports System.IO Public Class CustomResource Implements IDisposable Private _reader As StreamReader Public Sub New(ByVal filePath As String) _reader = New StreamReader(filePath) End Sub Public Sub ReadContent() Dim content As String = _reader.ReadToEnd() Console.WriteLine(content) End Sub Public Sub Dispose() Implements IDisposable.Dispose If _reader IsNot Nothing Then _reader.Dispose() _reader = Nothing End If End Sub End Class $vbLabelText $csharpLabel この例では、CustomResource クラスがディスポーザブルオブジェクトである StreamReader オブジェクトを管理します。 IDisposable インターフェイスを実装して Dispose メソッドを実装することで、このクラスのインスタンスで using ステートメントを使用できます。 CustomResource クラスで using ステートメントを使用する方法は以下の通りです: class Program { static void Main() { using (CustomResource resource = new CustomResource("example.txt")) { resource.ReadContent(); } } } class Program { static void Main() { using (CustomResource resource = new CustomResource("example.txt")) { resource.ReadContent(); } } } Friend Class Program Shared Sub Main() Using resource As New CustomResource("example.txt") resource.ReadContent() End Using End Sub End Class $vbLabelText $csharpLabel using ブロックが終了すると、Dispose メソッドが呼び出され、StreamReader オブジェクトが解放されます。 Using ステートメントによる例外処理 using ステートメントのもう一つの利点は、例外をより優雅に処理することを助けてくれることです。 using ブロック内で例外が発生した場合でも、リソースのDispose メソッドが呼び出され、適切にクリーンアップされることを保証します。 例えば、以下のコードを考えてみましょう: using System; using System.IO; class Program { static void Main() { try { using (StreamReader reader = new StreamReader("nonexistentfile.txt")) { string content = reader.ReadToEnd(); Console.WriteLine(content); } } catch (FileNotFoundException ex) { Console.WriteLine($"Error: {ex.Message}"); } } } using System; using System.IO; class Program { static void Main() { try { using (StreamReader reader = new StreamReader("nonexistentfile.txt")) { string content = reader.ReadToEnd(); Console.WriteLine(content); } } catch (FileNotFoundException ex) { Console.WriteLine($"Error: {ex.Message}"); } } } Imports System Imports System.IO Friend Class Program Shared Sub Main() Try Using reader As New StreamReader("nonexistentfile.txt") Dim content As String = reader.ReadToEnd() Console.WriteLine(content) End Using Catch ex As FileNotFoundException Console.WriteLine($"Error: {ex.Message}") End Try End Sub End Class $vbLabelText $csharpLabel この場合、コードが FileNotFoundException をスローすると、例外は catch ブロックによって捕捉され処理されます。 例外が using ブロック内で発生したとしても、StreamReader オブジェクトの Dispose メソッドは呼び出され、リソースが漏れることはありません。 IronPDFとUsingステートメントの活用 IronPDFは、C#と.NETアプリケーションでPDFファイルを作成、編集、抽出するための人気のあるライブラリです。 他のリソースを扱うライブラリと同様に、IronPDFもusingステートメントを利用して適切なリソース管理を行うことができます。 real-lifeなシナリオでの using ステートメントの力を示すために、HTML文字列からPDFドキュメントを作成するためにIronPDFを使ったusingステートメントの使い方を見てみましょう。 まず、あなたのプロジェクトに IronPDF NuGetパッケージをインストールしたことを確認してください: Install-Package IronPdf 次に、PDFファイルからすべてのデータを抽出しましょう: using IronPdf; class Program { static void Main() { // Using a using statement with IronPDF to ensure resources are managed using (PdfDocument pdfDocument = PdfDocument.FromFile("PDFData.pdf")) { string extractedText = pdfDocument.ExtractAllText(); Console.WriteLine(extractedText); } } } using IronPdf; class Program { static void Main() { // Using a using statement with IronPDF to ensure resources are managed using (PdfDocument pdfDocument = PdfDocument.FromFile("PDFData.pdf")) { string extractedText = pdfDocument.ExtractAllText(); Console.WriteLine(extractedText); } } } Imports IronPdf Friend Class Program Shared Sub Main() ' Using a using statement with IronPDF to ensure resources are managed Using pdfDocument As PdfDocument = PdfDocument.FromFile("PDFData.pdf") Dim extractedText As String = pdfDocument.ExtractAllText() Console.WriteLine(extractedText) End Using End Sub End Class $vbLabelText $csharpLabel このコードでは、「PDFData.pdf」という名前のPDFファイルをPdfDocument.FromFileメソッドを使って開きます。 このメソッドは PdfDocument インスタンスを返し、using ステートメントでラップします。 using ブロック内では、PdfDocument インスタンスでExtractAllTextを呼び出して、PDFからすべてのテキストを抽出します。 using ブロックを終了すると、Dispose メソッドが PdfDocument に自動的に呼び出され、保持していたリソースが解放されます。 PdfDocument で using ステートメントを使用することで、例外がプロセス中に発生した場合でも、テキストを抽出した後にPDFファイルが適切に閉じられることを保証します。 これは C# でリソースを効果的に管理するための using ステートメントの優れた例です。 まとめ 以上が using ステートメントの概要です! ディスポーザブルオブジェクトを効率的に処理し、1つまたは複数のリソースをシームレスに管理する方法を見てきました。 using ステートメントは、C# プロジェクトのコードをクリーンに保つだけでなく、読みやすさを向上させるのに役立ちます。 また、C#でのPDF操作のための強力なライブラリである IronPDF も紹介しました。 IronPDFと組み合わせて using ステートメントを使用することは、このコード機能の実際のアプリケーションを示し、概念とその重要性を補強します。 IronPDFを試してみる準備はできましたか? 30日間の無料試用版のIronPDFとIron Softwareのスイートを始めてみてください。 開発目的での使用は完全に無料なので、それがどのようなものであるかを実際に見ることができます。 気に入った場合は、IronPDFは$799からライセンスオプションを開始します。 さらに大きな節約をお求めなら、Iron Suite完全ソフトウェアパッケージをチェックしてください。ここでは、2つの価格ですべての9つのIron Softwareツールを手に入れることができます。 コーディングを楽しんでください! よくある質問 C#でusingステートメントの目的は何ですか? C#のusingステートメントは、ファイルハンドルやネットワーク接続など、IDisposableインターフェイスを実装するリソースを管理し、使用後に適切に破棄するために使用されます。 C#において、usingステートメントはどのようにしてリソースリークを防ぐのですか? usingステートメントは、オブジェクトが不要になったときにDisposeメソッドを自動的に呼び出し、例外が発生してもリソースが確実に解放されるようにすることで、リソースリークを防ぐのに役立ちます。 C#のusingブロックとusing宣言の違いは何ですか? usingブロックはコードを中括弧で囲み、ブロックの終わりで破棄を保証しますが、C# 8.0で導入されたusing宣言はより簡潔で、スコープを外れたときにリソースを自動的に破棄します。 カスタム C# クラスで IDisposable を実装するにはどうすればよいですか? カスタムクラスにIDisposableを実装するには、未管理リソースを解放するDisposeメソッドを定義し、usingステートメントを使って自動リソース管理を可能にします。 C#でusingステートメントは複数のリソースを処理できますか? はい、複数のusingステートメントを積み重ねることで複数のリソースを管理できますが、カンマで区切られた複数のリソースを持つ単一のusingステートメントはサポートされていません。 C#でusingステートメントがtry-finallyブロックより好まれる理由は? usingステートメントは、手動でtry-finallyブロックを実装してリソースの破棄を確実に行うよりも、コードを簡潔にし、自動リソース管理を提供するため、好まれます。 C#でPDFドキュメントを効果的に管理する方法は? IronPDFを使用してPDFドキュメントを効果的に管理できます。usingステートメントと統合し、テキスト抽出のような操作後にドキュメントインスタンスが適切に閉じられるようにします。 C#開発向けのPDFライブラリのトライアルはありますか? はい、特定のPDFライブラリは30日間の無料トライアルを提供しており、購入前にその機能を探ることができます。 Curtis Chau 今すぐエンジニアリングチームとチャット テクニカルライター Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。 関連する記事 更新日 9月 4, 2025 RandomNumberGenerator C# RandomNumberGenerator C#クラスを使用すると、PDF生成および編集プロジェクトを次のレベルに引き上げることができます 詳しく読む 更新日 9月 4, 2025 C# String Equals(開発者向けの仕組み) 強力なPDFライブラリであるIronPDFと組み合わせることで、switchパターンマッチングは、ドキュメント処理のためのよりスマートでクリーンなロジックを構築できます 詳しく読む 更新日 8月 5, 2025 C# Switch Pattern Matching(開発者向けの仕組み) 強力なPDFライブラリであるIronPDFと組み合わせることで、switchパターンマッチングは、ドキュメント処理のためのよりスマートでクリーンなロジックを構築できます 詳しく読む C# Extension Methods (開発者向けの仕組み)Visual C++ 再頒布可能とは何...
更新日 9月 4, 2025 RandomNumberGenerator C# RandomNumberGenerator C#クラスを使用すると、PDF生成および編集プロジェクトを次のレベルに引き上げることができます 詳しく読む
更新日 9月 4, 2025 C# String Equals(開発者向けの仕組み) 強力なPDFライブラリであるIronPDFと組み合わせることで、switchパターンマッチングは、ドキュメント処理のためのよりスマートでクリーンなロジックを構築できます 詳しく読む
更新日 8月 5, 2025 C# Switch Pattern Matching(開発者向けの仕組み) 強力なPDFライブラリであるIronPDFと組み合わせることで、switchパターンマッチングは、ドキュメント処理のためのよりスマートでクリーンなロジックを構築できます 詳しく読む