.NET ヘルプ

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

更新済み 6月 6, 2024
共有:

IListの紹介

IListは、.NETフレームワークのコレクションネームスペースの一部です。 それは、インデックスを用いて個別にアクセスできるオブジェクトのコレクションの設計図を提供する、ジェネリックではないコレクションインターフェースです。 配列とは異なり、 IList(アイリスト) 必要に応じてコレクションから要素を追加または削除できるため、動的な数のオブジェクト値要素を許可します。 それは、.NET Frameworkのすべての非ジェネリックリストの基底インターフェイスとして機能し、配列よりも柔軟な方法でオブジェクトのコレクションを管理する手段を提供します。 以下に日本語に翻訳した内容を記載します:

`IList`インターフェースについて学びましょう
``` [IronPDFライブラリ](/) このチュートリアルで。

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

`public interface IList` の宣言は、.NET Framework の Collections 名前空間によって指定される `IList` 契約に準拠したカスタム コレクションを C# で作成するための基本的な部分です。 `IList`には、コレクション内の要素にアクセスし、要素の数を数え、要素の追加、挿入、または削除によってコレクションを変更するためのプロパティとメソッドが含まれています。 `IList`インターフェースで定義されている主要なプロパティとメソッドの一部を以下に示します:
* `IsFixedSize` や `IsReadOnly` のようなプロパティは、コレクションが固定サイズか、読み取り専用かどうかをそれぞれ示します。
* コレクション内の要素を変更するために、`Add`、void `Insert`、`Remove`、および `RemoveAt` のようなメソッドが使用されます。 要素を追加、挿入、削除することができます。

 * 次の内容を日本語に翻訳してください:

`IndexOf`メソッドは要素を見つけるためのもので、`Item`プロパティは (C#でのインデクサ) インデックスに基づいて要素の取得および設定を可能にします。

## パブリックインターフェイス `IList` の実用的な使用法

`IList` の動作を示すために、シンプルな例を作成してみましょう。 この一般的なバージョンの例では、`IList`を宣言し、アイテムを追加し、その内容を反復処理する方法を示します。

### `IList`を作成および変更する

まず、`IList`を宣言して項目を追加する方法を見てみましょう:

```cs
using System;
using System.Collections;
class Program
{
    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 interface using count property
        Console.WriteLine($"Number of elements: {myIList.Count}");
        // Access Elements
        foreach (var element in myIList)
        {
            Console.WriteLine(element);
        }
    }
}

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

インデックスベースのアクセスおよび修正

要素にインデックスでアクセスし、修正することは IList の重要な機能です。 以下の IList の例は、その方法を示しています:

// 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]}");
// 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]}");
' 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)}")
VB   C#

カスタム IList の実装

カスタマイズされたコレクションが必要な場合があり、その場合 IList を継承することが求められます。 これにより、要素の格納、アクセス、および変更方法に対するより多くの制御が可能になります。 以下は、IListを実装するシンプルなカスタムコレクションの例です:

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;
// int add
    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();
    }
}
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;
// int add
    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();
    }
}
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
' int add
	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
VB   C#

この CustomCollection クラスは ArrayList をカプセル化しており、このクラス自体が IList を実装しています。 私たちの CustomCollection は基礎となる ArrayList に呼び出しを転送し、IList を実装する他のコレクションと同様に動作することを可能にします。 この例は、インデックスでアクセスでき、修正可能なコレクションの作成を示しています。 (追加、挿入、または削除された項目)また、IListを実装する標準の .NET コレクションと同様に、反復処理を行うことができます。

IListの高度な操作

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

// 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}");
// 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}");
' 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}")
VB   C#

これらの操作は、特定のアイテムの存在や位置をコレクション全体を繰り返すことなく確認する必要がある場合に、特に役立ちます。

IronPDF: C# PDFライブラリ

C# で IList (開発者向けの動作方法): 図1 - IronPDF

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

コード例

以下は、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
VB   C#

この例では、IList<string> はフルーツの名前のコレクションを保存するために使用されます。 GeneratePDFFromList メソッドはこのリストを反復処理し、各アイテムを箇条書きリストに含むHTML文字列を構築します。IronPDFの ChromePdfRenderer レンダラーは、このHTMLコンテンツをPDFドキュメントに変換し、その後ファイルに保存されます。

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

結論

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

この初心者向けガイドは、C#のIListの基本と実用的な使用法について説明することを目的としています。 サンプルにはシンプルな使用方法からカスタム実装まであり、IListがC#開発者のツールキットにおいて強力なツールであることが明白です。 データのコレクションを操作する場合でも、独自のコレクション型を構築する場合でも、IListは効果的なソフトウェア開発に必要な機能と柔軟性を提供します。 IronPDFは 無料試用 興味のあるユーザーのために、ライセンスは$749から取得可能です。

< 以前
C# リンクドリスト (開発者向けの仕組み)
次へ >
開発者向けのPolly Retry (その仕組み)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >