フッターコンテンツにスキップ
.NETヘルプ

C# iList(開発者向けの動作方法)

IListの紹介

IListは、.NET FrameworkのCollections名前空間の一部です。 これは、インデックスで個別にアクセス可能なオブジェクトのコレクションの設計図を提供する、非ジェネリックなコレクションインターフェースです。 配列とは異なり、IListは動的数のオブジェクト値要素を許容し、必要に応じてコレクションから要素を追加または削除できます。 これは、.NET Framework内のすべての非ジェネリックリストの基本インターフェースとして機能し、配列よりも柔軟な方法でオブジェクトの集合を管理する手段を提供します。 このチュートリアルでは、IListインターフェースとIronPDF C# PDFライブラリについて学びます。

IListインターフェースの理解

public interface IListの宣言は、.NET FrameworkのCollections名前空間によって指定されたIList契約に従うC#のカスタムコレクションを作成するための基本的な部分です。 IListには、コレクションの要素をアクセス、カウント、要素の追加や挿入、または削除でコレクションを変更するためのプロパティとメソッドが含まれています。 IListインターフェースで定義されている主要プロパティとメソッドをいくつか紹介します:

  • IsFixedSizeIsReadOnlyのようなプロパティは、コレクションが固定サイズか読み取り専用であるかを示します。
  • AddInsertRemoveRemoveAtのようなメソッドは、コレクション内の要素を変更するために使用されます。 要素を追加、挿入、削除できます。
  • IndexOfメソッドは要素を見つけるため、Itemプロパティ(もしくはC#でのインデクサ)はインデックスに基づいて要素を取得または設定することができます。

IListインターフェースの実践的な使い方

IListがどのように機能するかを示すために、簡単な例を作成しましょう。 この例では、IListを宣言し、それにアイテムを追加し、その内容を反復処理する方法を示します。

IListの作成と変更

まず、IListを宣言し、アイテムを追加する方法を見てみましょう:

using System;
using System.Collections;

class Program
{
    static void Main(string[] args)
    {
        // Creating an IList instance
        IList myIList = new ArrayList();

        // Adding elements to the IList
        myIList.Add("Hello");
        myIList.Add(10);
        myIList.Add(new object());

        // Displaying the number of values in the IList using the Count property
        Console.WriteLine($"Number of elements: {myIList.Count}");

        // Accessing elements using a loop
        foreach (var element in myIList)
        {
            Console.WriteLine(element);
        }
    }
}
using System;
using System.Collections;

class Program
{
    static void Main(string[] args)
    {
        // Creating an IList instance
        IList myIList = new ArrayList();

        // Adding elements to the IList
        myIList.Add("Hello");
        myIList.Add(10);
        myIList.Add(new object());

        // Displaying the number of values in the IList using the Count property
        Console.WriteLine($"Number of elements: {myIList.Count}");

        // Accessing elements using a loop
        foreach (var element in myIList)
        {
            Console.WriteLine(element);
        }
    }
}
Imports System
Imports System.Collections

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Creating an IList instance
		Dim myIList As IList = New ArrayList()

		' Adding elements to the IList
		myIList.Add("Hello")
		myIList.Add(10)
		myIList.Add(New Object())

		' Displaying the number of values in the IList using the Count property
		Console.WriteLine($"Number of elements: {myIList.Count}")

		' Accessing elements using a loop
		For Each element In myIList
			Console.WriteLine(element)
		Next element
	End Sub
End Class
$vbLabelText   $csharpLabel

この例では、ArrayListを使用してIListインスタンスを作成しましたが、このクラスはIListを実装しています。 さまざまな種類のオブジェクトを追加して、IListが任意のオブジェクトを保持できることを示しています。 最後に、コレクションを反復処理し、各要素を印刷しました。

インデックスに基づくアクセスおよび変更

インデックスを使用して要素にアクセスし、変更することはIListの重要な機能です。 次の例は、それを行う方法を示しています:

using System;
using System.Collections;

class Program
{
    static void Main(string[] args)
    {
        IList myIList = new ArrayList { "Hello", 10, new object() };

        // Accessing an element by index
        object value = myIList[1];
        Console.WriteLine($"Element at index 1: {value}");

        // Modifying an element by index
        myIList[1] = 20;
        Console.WriteLine($"Modified element at index 1: {myIList[1]}");
    }
}
using System;
using System.Collections;

class Program
{
    static void Main(string[] args)
    {
        IList myIList = new ArrayList { "Hello", 10, new object() };

        // Accessing an element by index
        object value = myIList[1];
        Console.WriteLine($"Element at index 1: {value}");

        // Modifying an element by index
        myIList[1] = 20;
        Console.WriteLine($"Modified element at index 1: {myIList[1]}");
    }
}
Imports System
Imports System.Collections

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim myIList As IList = New ArrayList From { "Hello", 10, New Object() }

		' Accessing an element by index
		Dim value As Object = myIList(1)
		Console.WriteLine($"Element at index 1: {value}")

		' Modifying an element by index
		myIList(1) = 20
		Console.WriteLine($"Modified element at index 1: {myIList(1)}")
	End Sub
End Class
$vbLabelText   $csharpLabel

カスタムIListを実装する

時々、IListを継承するカスタムのコレクションが必要な場合があります。 これにより、要素の保管、アクセス、変更方法に対するよりよい制御が可能になります。 IListを実装する簡単なカスタムコレクションの例は以下の通りです:

using System;
using System.Collections;

public class CustomCollection : IList
{
    private ArrayList _innerList = new ArrayList();

    public object this[int index]
    {
        get => _innerList[index];
        set => _innerList[index] = value;
    }

    public bool IsFixedSize => _innerList.IsFixedSize;
    public bool IsReadOnly => _innerList.IsReadOnly;
    public int Count => _innerList.Count;
    public bool IsSynchronized => _innerList.IsSynchronized;
    public object SyncRoot => _innerList.SyncRoot;

    public int Add(object value)
    {
        return _innerList.Add(value);
    }

    public void Clear()
    {
        _innerList.Clear();
    }

    public bool Contains(object value)
    {
        return _innerList.Contains(value);
    }

    public int IndexOf(object value)
    {
        return _innerList.IndexOf(value);
    }

    public void Insert(int index, object value)
    {
        _innerList.Insert(index, value);
    }

    public void Remove(object value)
    {
        _innerList.Remove(value);
    }

    public void RemoveAt(int index)
    {
        _innerList.RemoveAt(index);
    }

    public void CopyTo(Array array, int index)
    {
        _innerList.CopyTo(array, index);
    }

    public IEnumerator GetEnumerator()
    {
        return _innerList.GetEnumerator();
    }
}
using System;
using System.Collections;

public class CustomCollection : IList
{
    private ArrayList _innerList = new ArrayList();

    public object this[int index]
    {
        get => _innerList[index];
        set => _innerList[index] = value;
    }

    public bool IsFixedSize => _innerList.IsFixedSize;
    public bool IsReadOnly => _innerList.IsReadOnly;
    public int Count => _innerList.Count;
    public bool IsSynchronized => _innerList.IsSynchronized;
    public object SyncRoot => _innerList.SyncRoot;

    public int Add(object value)
    {
        return _innerList.Add(value);
    }

    public void Clear()
    {
        _innerList.Clear();
    }

    public bool Contains(object value)
    {
        return _innerList.Contains(value);
    }

    public int IndexOf(object value)
    {
        return _innerList.IndexOf(value);
    }

    public void Insert(int index, object value)
    {
        _innerList.Insert(index, value);
    }

    public void Remove(object value)
    {
        _innerList.Remove(value);
    }

    public void RemoveAt(int index)
    {
        _innerList.RemoveAt(index);
    }

    public void CopyTo(Array array, int index)
    {
        _innerList.CopyTo(array, index);
    }

    public IEnumerator GetEnumerator()
    {
        return _innerList.GetEnumerator();
    }
}
Imports System
Imports System.Collections

Public Class CustomCollection
	Implements IList

	Private _innerList As New ArrayList()

	Default Public Property Item(ByVal index As Integer) As Object Implements IList.Item
		Get
			Return _innerList(index)
		End Get
		Set(ByVal value As Object)
			_innerList(index) = value
		End Set
	End Property

	Public ReadOnly Property IsFixedSize() As Boolean Implements IList.IsFixedSize
		Get
			Return _innerList.IsFixedSize
		End Get
	End Property
	Public ReadOnly Property IsReadOnly() As Boolean Implements IList.IsReadOnly
		Get
			Return _innerList.IsReadOnly
		End Get
	End Property
	Public ReadOnly Property Count() As Integer Implements System.Collections.ICollection.Count
		Get
			Return _innerList.Count
		End Get
	End Property
	Public ReadOnly Property IsSynchronized() As Boolean Implements System.Collections.ICollection.IsSynchronized
		Get
			Return _innerList.IsSynchronized
		End Get
	End Property
	Public ReadOnly Property SyncRoot() As Object Implements System.Collections.ICollection.SyncRoot
		Get
			Return _innerList.SyncRoot
		End Get
	End Property

	Public Function Add(ByVal value As Object) As Integer Implements IList.Add
		Return _innerList.Add(value)
	End Function

	Public Sub Clear() Implements IList.Clear
		_innerList.Clear()
	End Sub

	Public Function Contains(ByVal value As Object) As Boolean Implements IList.Contains
		Return _innerList.Contains(value)
	End Function

	Public Function IndexOf(ByVal value As Object) As Integer Implements IList.IndexOf
		Return _innerList.IndexOf(value)
	End Function

	Public Sub Insert(ByVal index As Integer, ByVal value As Object) Implements IList.Insert
		_innerList.Insert(index, value)
	End Sub

	Public Sub Remove(ByVal value As Object) Implements IList.Remove
		_innerList.Remove(value)
	End Sub

	Public Sub RemoveAt(ByVal index As Integer) Implements IList.RemoveAt
		_innerList.RemoveAt(index)
	End Sub

	Public Sub CopyTo(ByVal array As Array, ByVal index As Integer) Implements System.Collections.ICollection.CopyTo
		_innerList.CopyTo(array, index)
	End Sub

	Public Function GetEnumerator() As IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
		Return _innerList.GetEnumerator()
	End Function
End Class
$vbLabelText   $csharpLabel

このCustomCollectionクラスは、IListを実装するクラスであるArrayListをカプセル化しています。 私たちのCustomCollectionは、基底ArrayListに呼び出しを転送し、他のIListを実装するコレクションのように振る舞うことができます。 この例は、.NETに組み込まれているIListを実装する任意のコレクションのように、インデックスによるアクセス、変更(アイテムの追加、挿入、削除)が可能であり、反復処理も可能であるコレクションを作成する方法を実証しています。

IListの進んだ操作

基礎的な追加、削除、アクセス操作を超えて、IListはより複雑な操作やクエリを可能にします。 たとえば、コレクションに特定のオブジェクトが含まれているかを確認したり、コレクション内のオブジェクトのインデックスを見つけることは、特定のアプリケーションにとって重要な場合もあります:

using System;
using System.Collections;

class Program
{
    static void Main(string[] args)
    {
        IList myIList = new ArrayList { "Hello", 10, new object() };

        // Check if the IList contains a specific object
        bool contains = myIList.Contains(10); // Assuming 10 was added previously
        Console.WriteLine($"Contains 10: {contains}");

        // Find the index of a specific object
        int index = myIList.IndexOf(10);
        Console.WriteLine($"Index of 10: {index}");
    }
}
using System;
using System.Collections;

class Program
{
    static void Main(string[] args)
    {
        IList myIList = new ArrayList { "Hello", 10, new object() };

        // Check if the IList contains a specific object
        bool contains = myIList.Contains(10); // Assuming 10 was added previously
        Console.WriteLine($"Contains 10: {contains}");

        // Find the index of a specific object
        int index = myIList.IndexOf(10);
        Console.WriteLine($"Index of 10: {index}");
    }
}
Imports System
Imports System.Collections

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim myIList As IList = New ArrayList From { "Hello", 10, New Object() }

		' Check if the IList contains a specific object
		Dim contains As Boolean = myIList.Contains(10) ' Assuming 10 was added previously
		Console.WriteLine($"Contains 10: {contains}")

		' Find the index of a specific object
		Dim index As Integer = myIList.IndexOf(10)
		Console.WriteLine($"Index of 10: {index}")
	End Sub
End Class
$vbLabelText   $csharpLabel

これらの操作は、特定のアイテムの存在や位置を、コレクション全体を反復処理しないで判定する必要があるときに、オブジェクトのコレクションを扱う際に特に便利です。

IronPDF: C# PDFライブラリ

C# iList(開発者向けの動作):図1 - IronPDF

IronPDFは、.NETアプリケーション内で直接PDFドキュメントの作成と操作を可能にする.NET開発者向けのPDFライブラリです。 HTMLからPDFドキュメントへの変換、画像、ウェブページをPDFに変換することをサポートしています。 開発者は、このライブラリを使用してアプリケーションに簡単にPDF機能を追加できます。 IronPDFには、PDFファイルの編集、結合、分割機能も含まれており、PDF操作を包括的に制御できます。

IronPDFは、オリジナルのレイアウトやスタイルを正確に維持するHTMLからPDFへの変換に優れています。 レポート、請求書、ドキュメントなどのウェブベースのコンテンツからPDFを作成するのに最適です。 HTMLファイル、URL、生のHTML文字列をサポートしているため、IronPDFは簡単に高品質のPDFドキュメントを生成できます。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

コード例

IronPDFとIListインターフェースを使用して文字列のリストから単純なPDFドキュメントを生成することを示す簡単な例を次に示します:

using IronPdf;
using System.Collections.Generic;

public class PDFGenerator
{
    public static void GeneratePDFFromList(IList<string> dataList)
    {
        // Initialize the HtmlToPdf renderer
        var renderer = new ChromePdfRenderer();

        // Start building HTML content from the dataList
        var htmlContent = "<h1>My Data List</h1><ul>";
        foreach (var item in dataList)
        {
            htmlContent += $"<li>{item}</li>";
        }
        htmlContent += "</ul>";

        // Convert HTML string to PDF
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

        // Save the PDF to a file
        pdfDocument.SaveAs("DataList.pdf");
    }
}

// Example usage
class Program
{
    static void Main(string[] args)
    {
        License.LicenseKey = "License-Key";
        IList<string> myDataList = new List<string> { "Apple", "Banana", "Cherry" };
        PDFGenerator.GeneratePDFFromList(myDataList);
    }
}
using IronPdf;
using System.Collections.Generic;

public class PDFGenerator
{
    public static void GeneratePDFFromList(IList<string> dataList)
    {
        // Initialize the HtmlToPdf renderer
        var renderer = new ChromePdfRenderer();

        // Start building HTML content from the dataList
        var htmlContent = "<h1>My Data List</h1><ul>";
        foreach (var item in dataList)
        {
            htmlContent += $"<li>{item}</li>";
        }
        htmlContent += "</ul>";

        // Convert HTML string to PDF
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

        // Save the PDF to a file
        pdfDocument.SaveAs("DataList.pdf");
    }
}

// Example usage
class Program
{
    static void Main(string[] args)
    {
        License.LicenseKey = "License-Key";
        IList<string> myDataList = new List<string> { "Apple", "Banana", "Cherry" };
        PDFGenerator.GeneratePDFFromList(myDataList);
    }
}
Imports IronPdf
Imports System.Collections.Generic

Public Class PDFGenerator
	Public Shared Sub GeneratePDFFromList(ByVal dataList As IList(Of String))
		' Initialize the HtmlToPdf renderer
		Dim renderer = New ChromePdfRenderer()

		' Start building HTML content from the dataList
		Dim htmlContent = "<h1>My Data List</h1><ul>"
		For Each item In dataList
			htmlContent &= $"<li>{item}</li>"
		Next item
		htmlContent &= "</ul>"

		' Convert HTML string to PDF
		Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)

		' Save the PDF to a file
		pdfDocument.SaveAs("DataList.pdf")
	End Sub
End Class

' Example usage
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		License.LicenseKey = "License-Key"
		Dim myDataList As IList(Of String) = New List(Of String) From {"Apple", "Banana", "Cherry"}
		PDFGenerator.GeneratePDFFromList(myDataList)
	End Sub
End Class
$vbLabelText   $csharpLabel

この例では、IList<string>を使用して果物名のコレクションを格納しています。 その後、GeneratePDFFromListメソッドはこのリストを反復処理し、各アイテムを含むHTML文字列を構築します。 IronPDFのChromePdfRendererはこのHTMLコンテンツをPDFドキュメントに変換し、それをファイルに保存します。

C# iList(開発者向けの動作):図2 - PDF出力

結論

C# iList(開発者向けの動作):図3 - ライセンス

この初心者向けガイドは、C#におけるIListの基本と実践的な使用法をカバーすることを目的としていました。 簡単な使用法からカスタム実装までの例を通じて、IListはC#開発者のツールキットにおいて強力なツールであることが明らかです。 データのコレクションを操作する場合でも、コレクションタイプを作成する場合でも、IListは効果的なソフトウェア開発に必要な機能と柔軟性を提供します。 IronPDFはPDFライブラリの無料トライアルを興味のあるユーザーに提供しており、ライセンスは$799から利用可能です。

よくある質問

C# における IList インターフェイスとは何ですか?

`IList` インターフェイスは、.NET Framework の Collections 名前空間の一部で、インデックスによってアクセスできる動的なコレクションの作成に使用されます。追加、挿入、削除、要素へのアクセスのためのメソッドを提供し、静的配列よりも柔軟性を提供します。

C#でHTMLをPDFに変換する方法は?

C# で IronPDF の `RenderHtmlAsPdf` メソッドを使用して HTML を PDF に変換できます。これにより、HTML 文字列、ファイル、URL を高品質な PDF ドキュメントに変換することができます。

IList インターフェイスの主なメソッドは何ですか?

`IList` インターフェイスの主要なメソッドには、`Add`、`Insert`、`Remove`、`RemoveAt`、および `IndexOf` が含まれます。これらのメソッドは、コレクション内の要素を動的に管理および変更するために不可欠です。

C# でカスタム IList を作成するにはどうすればよいですか?

C# でカスタム `IList` を作成するためには、クラス内で `IList` インターフェイスを実装し、`Add`、`Remove`、`IndexOf` などの必要なメソッドやプロパティをオーバーライドして、コレクションが要素をどのように処理するかをカスタマイズします。

IronPDF はどのようにして HTML から PDF を作成しますか?

IronPDF は `ChromePdfRenderer` クラスを使用して HTML コンテンツを PDF に変換します。これにより、HTML 文字列、ファイル、URL からの変換をサポートし、ウェブコンテンツからの正確な PDF 作成を保証します。

データの IList から PDF を生成できますか?

はい、IList を繰り返し処理して HTML 文字列を構築し、IronPDF の `ChromePdfRenderer` を使用して HTML を PDF ドキュメントに変換し、`SaveAs` メソッドを使用して保存することで、IList から PDF を生成できます。

IList がサポートしている高度な操作は何ですか?

`IList` の高度な操作には、`Contains` を使用してコレクションが特定のオブジェクトを含んでいるかどうかを確認したり、`IndexOf` を使用してオブジェクトのインデックスを見つけたりすることが含まれます。これらの機能は、要素を手動で検索する必要なく、効率的にコレクションを管理するのに役立ちます。

C# で PDF 生成の問題をトラブルシュートするにはどうすればよいですか?

C# で PDF 生成に問題が発生した場合は、HTML コンテンツが正しくフォーマットされていること、最新の IronPDF バージョンを使用していることを確認してください。変換プロセス中にスローされた例外をチェックして、さらに洞察を得てください。

Curtis Chau
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。