検索
ホームページバックエンド開発C#.Net チュートリアルC#の基礎知識集 基礎知識(17) ILiestインターフェース - ジェネリックス

ArrayList に値の型を挿入するとボックス化操作がトリガーされ、次のように値の型を削除するにはボックス化を解除する必要があります

            ArrayList myArrayList = new ArrayList();

            myArrayList.Add(40);//装箱

            myArrayList.Add(80);//装箱
            
            Int32 a1 = (Int32)myArrayList[0];//拆箱

            Int32 a2 = (Int32)myArrayList[1];//拆箱

これによりパフォーマンスの消費が発生します。梱包の詳しい説明は次の記事をご覧ください。
これらの問題を解決するために、C# にはジェネリックをサポートする IList インターフェイスがあります。実際には、構造は IList と同じですが、ジェネリックが追加されています。

 /// <summary>
    /// 泛型集合类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class List<T> : IList<T>, IList
    {
        /// <summary>
        /// 泛型迭代器
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public struct Enumertor<T> : IEnumerator, IEnumerator<T>
        {
            //迭代索引
            private int index;

            //迭代器所属的集合对象引用
            private List<T> list;

            public Enumertor(List<T> container)
            {
                this.list = container;

                this.index = -1;
            }

            public void Dispose()
            {
            }

           /// <summary>
           /// 显示实现IEnumerator的Current属性
           /// </summary>
            object IEnumerator.Current
            {
                get
                {
                    return list[index];
                }
            }

            /// <summary>
            /// 实现IEnumerator<T>的Current属性
            /// </summary>
            public T Current
            {
                get
                {
                    return list[index];
                }
            }

            /// <summary>
            /// 迭代器指示到下一个数据位置
            /// </summary>
            /// <returns></returns>
            public bool MoveNext()
            {
                if (this.index < list.Count)
                {
                    ++this.index;
                }

                return this.index < list.Count;
            }

            public void Reset()
            {
                this.index = -1;
            }
        }

        /// <summary>
        /// 保存数据的数组,T类型则体现了泛型的作用。
        /// </summary>
        private T[] array;

        /// <summary>
        /// 当前集合的长度
        /// </summary>
        private int count;

        /// <summary>
        /// 默认构造函数
        /// </summary>
        public List()
            : this(1)
        {

        }

        public List(int capacity)
        {
            if (capacity < 0)
            {
                throw new Exception("集合初始长度不能小于0");
            }

            if (capacity == 0)
            {
                capacity = 1;
            }

            this.array = new T[capacity];
        }

        /// <summary>
        /// 集合长度
        /// </summary>
        public int Count
        {
            get
            {
                return this.count;
            }
        }

        /// <summary>
        /// 集合实际长度
        /// </summary>
        public int Capacity
        {
            get
            {
                return this.array.Length;
            }
        }

        /// <summary>
        /// 是否固定大小
        /// </summary>
        public bool IsFixedSize
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// 是否只读
        /// </summary>
        public bool IsReadOnly
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// 是否可同属性
        /// </summary>
        public bool IsSynchronized
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// 同步对象
        /// </summary>
        public object SyncRoot
        {
            get
            {
                return null;
            }
        }

        /// <summary>
        /// 长度不够时,重新分配长度足够的数组
        /// </summary>
        /// <returns></returns>
        private T[] GetNewArray()
        {
            return new T[(this.array.Length + 1) * 2];
        }

        /// <summary>
        /// 实现IList<T>Add方法
        /// </summary>
        /// <param name="value"></param>
        public void Add(T value)
        {
            int newCount = this.count + 1;

            if (this.array.Length < newCount)
            {
                T[] newArray = GetNewArray();

                Array.Copy(this.array, newArray, this.count);

                this.array = newArray;
            }

            this.array[this.count] = value;

            this.count = newCount;
        }

        /// <summary>
        /// 向集合末尾添加对象
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
         int IList.Add(object value)
        {
            ((IList<T>)this).Add((T)value);

            return this.count - 1;
        }

        /// <summary>
        /// 实现IList<T>索引器
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public T this[int index]
        {
            get
            {
                if (index < 0 || index >= this.count)
                {
                    throw new ArgumentOutOfRangeException("index");
                }

                return this.array[index];
            }

            set
            {
                if (index < 0 || index >= this.count)
                {
                    throw new ArgumentOutOfRangeException("index");
                }

                this.array[index] = value;
            }
        }

        /// <summary>
        /// 显示实现IList接口的索引器
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        object IList.this[int index]
        {
            get
            {
                return ((IList<T>)this)[index];
            }

            set
            {
                ((IList<T>)this)[index] = (T)value;
            }
        }

        /// <summary>
        /// 删除集合中的元素
        /// </summary>
        /// <param name="index"></param>
        /// <param name="count"></param>
        public void RemoveRange(int index, int count)
        {
            if (index < 0)
            {
                throw new ArgumentOutOfRangeException("index");
            }

            int removeIndex = index + count;

            if (count < 0 || removeIndex > this.count)
            {
                throw new ArgumentOutOfRangeException("index");
            }

            Array.Copy(this.array, index + 1, this.array, index + count - 1, this.count - removeIndex);

            this.count -= count;
        }

        /// <summary>
        /// 实现IList<T>接口的indexOf方法
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public int IndexOf(T value)
        {
            int index = 0;

            if (value == null)
            {
                while (index < this.count)
                {
                    if (this.array[index] == null)
                    {
                        return index;
                    }

                    ++index;
                }
            }
            else
            {
                while (index < this.count)
                {
                    if (value.Equals(this.array[index]))
                    {
                        return index;
                    }

                    ++index;
                }
            }
            return -1;
        }

        /// <summary>
        /// 显示实现IList接口的IndexOf方法
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
         int IList.IndexOf(object value)
        {
            return ((IList<T>)this).IndexOf((T)value);
        }

        /// <summary>
        /// 查找对应数组项
        /// </summary>
        /// <param name="o"></param>
        /// <param name="compar"></param>
        /// <returns></returns>
        public int IndexOf(object o, IComparer compar)
        {
            int index = 0;

            while (index < this.count)
            {
                if (compar.Compare(this.array[index], o) == 0)
                {
                    return index;
                }

                ++index;
            }

            return -1;
        }

        /// <summary>
        /// 实现IList<T>接口的Remove方法
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool Remove(T value)
        {
            int index = this.IndexOf(value);

            if (index >= 0)
            {
                this.RemoveRange(index, 1);

                return true;
            }

            return false;
        }

        /// <summary>
        /// 显示实现IList接口的Remove方法,此处显示实现
        /// </summary>
        /// <param name="value"></param>
        void IList.Remove(object value)
        {
            ((IList<T>)this).Remove((T)value);
        }

        /// <summary>
        /// 从集合指定位置删除对象的引用
        /// </summary>
        /// <param name="index"></param>
        public void RemoveAt(int index)
        {
            RemoveRange(index, 1);
        }

        /// <summary>
        /// 弹出集合的最后一个元素
        /// </summary>
        /// <returns></returns>
        public object PopBack()
        {
            object o = this.array[this.count - 1];

            RemoveAt(this.count - 1);

            return o;
        }

        /// <summary>
        /// 弹出集合第一个对象
        /// </summary>
        /// <returns></returns>
        public object PopFront()
        {
            object o = this.array[0];

            RemoveAt(0);

            return o;
        }

        /// <summary>
        /// 实现IList<T>接口的Insert方法
        /// </summary>
        /// <param name="index"></param>
        /// <param name="value"></param>
        public void Insert(int index, T value)
        {
            if (index >= this.count)
            {
                throw new ArgumentOutOfRangeException("index");
            }

            int newCount = this.count + 1;

            if (this.array.Length < newCount)
            {
                T[] newArray = GetNewArray();

                Array.Copy(this.array, newArray, index);

                newArray[index] = value;

                Array.Copy(this.array, index, newArray, index + 1, this.count - index);

                this.array = newArray;
            }
            else
            {
                Array.Copy(this.array, index, this.array, index + 1, this.count - index);

                this.array[index] = value;
            }

            this.count = newCount;
        }

        /// <summary>
        /// 显示实现IList接口的Insert方法
        /// </summary>
        /// <param name="index"></param>
        /// <param name="value"></param>
        void IList.Insert(int index, object value)
        {
            ((IList<T>)this).Insert(index, (T)value);
        }

        /// <summary>
        /// 实现IList<T>接口的Contains方法
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool Contains(T value)
        {
            return this.IndexOf(value) >= 0;
        }

        /// <summary>
        /// 显示实现IList<T>接口的Contains方法
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        bool IList.Contains(object value)
        {
            return ((IList<T>)this).IndexOf((T)value) >= 0;
        }

        /// <summary>
        /// 将集合压缩为实际长度
        /// </summary>
        public void TrimToSize()
        {
            if (this.array.Length > this.count)
            {
                T[] newArray = null;

                if (this.count > 0)
                {
                    newArray = new T[this.count];

                    Array.Copy(this.array, newArray, this.count);
                }
                else
                {
                    newArray = new T[1];
                }

                this.array = newArray;
            }
        }

        /// <summary>
        /// 清空集合
        /// </summary>
        public void Clear()
        {
            this.count = 0;
        }

        /// <summary>
        /// 实现IEnumerable接口的GetEnumerator方法
        /// </summary>
        /// <returns></returns>
        public IEnumerator<T> GetEnumerator()
        {
            Enumertor<T> ator = new Enumertor<T>(this);

            return ator;
        }

        /// <summary>
        /// 显示实现IEnumerable接口的GetEnumerator方法
        /// </summary>
        /// <returns></returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return ((IEnumerable<T>)this).GetEnumerator();
        }

        /// <summary>
        /// 实现ICollection<T>接口的CopyTo方法
        /// </summary>
        /// <param name="array"></param>
        /// <param name="index"></param>
        public void CopyTo(T[] array, int index)
        {
            Array.Copy(this.array, 0, array, index, this.count);
        }

        /// <summary>
        /// 显示实现实现ICollection<T>接口的CopyTo方法
        /// </summary>
        /// <param name="array"></param>
        /// <param name="index"></param>
        void ICollection.CopyTo(Array array, int index)
        {
            Array.Copy(this.array, 0, array, index, this.count);
        }
    }

Call:

 static void Main(string[] args)
        {
            //由于已经指定了int,因此加入值类型不会有装箱拆箱操作。
            List<int> tList = new List<int>();

            tList.Add(25);

            tList.Add(30);

            foreach (int n in tList)
            {
                Console.WriteLine(n);
            }

            Console.ReadLine();
        }

以上は C# の基礎知識の内容です 基礎知識 (17) ILiest インターフェイス - ジェネリックス 関連内容については、PHP 中国語 Web サイト (www.php.cn) をご覧ください。 )!


声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
c#.netの継続的な関連性:現在の使用法を見るc#.netの継続的な関連性:現在の使用法を見るApr 16, 2025 am 12:07 AM

C#.NETは、複数のアプリケーション開発をサポートする強力なツールとライブラリを提供するため、依然として重要です。 1)C#は.NETフレームワークを組み合わせて、開発を効率的かつ便利にします。 2)C#のタイプの安全性とゴミ収集メカニズムは、その利点を高めます。 3).NETは、クロスプラットフォームの実行環境とリッチAPIを提供し、開発の柔軟性を向上させます。

Webからデスクトップまで:C#.NETの汎用性Webからデスクトップまで:C#.NETの汎用性Apr 15, 2025 am 12:07 AM

c#.netisversatileforbothwebanddesktopdevelopment.1)forweb、useasp.netfordynamicapplications.2)fordesktop、equindowsorwpfforrichinterfaces.3)usexamarinforcross-platformdeveliment、enabling deshacrosswindows、

c#.net and the Future:新しいテクノロジーへの適応c#.net and the Future:新しいテクノロジーへの適応Apr 14, 2025 am 12:06 AM

C#と.NETは、継続的な更新と最適化を通じて、新しいテクノロジーのニーズに適応します。 1)C#9.0および.NET5は、レコードタイプとパフォーマンスの最適化を導入します。 2).Netcoreは、クラウドネイティブおよびコンテナ化されたサポートを強化します。 3)ASP.Netcoreは、最新のWebテクノロジーと統合されています。 4)ML.NETは、機械学習と人工知能をサポートしています。 5)非同期プログラミングとベストプラクティスはパフォーマンスを改善します。

c#.netはあなたにぴったりですか?その適用性の評価c#.netはあなたにぴったりですか?その適用性の評価Apr 13, 2025 am 12:03 AM

c#.netissuitableforenterprise-levelApplicationsとsystemduetoitsSystemdutyping、richlibraries、androbustperformance.

.NET内のC#コード:プログラミングプロセスの調査.NET内のC#コード:プログラミングプロセスの調査Apr 12, 2025 am 12:02 AM

.NETでのC#のプログラミングプロセスには、次の手順が含まれます。1)C#コードの作成、2)中間言語(IL)にコンパイルし、3).NETランタイム(CLR)によって実行される。 .NETのC#の利点は、デスクトップアプリケーションからWebサービスまでのさまざまな開発シナリオに適した、最新の構文、強力なタイプシステム、および.NETフレームワークとの緊密な統合です。

C#.NET:コアの概念とプログラミングの基礎を探るC#.NET:コアの概念とプログラミングの基礎を探るApr 10, 2025 am 09:32 AM

C#は、Microsoftによって開発された最新のオブジェクト指向プログラミング言語であり、.NETフレームワークの一部として開発されています。 1.C#は、カプセル化、継承、多型を含むオブジェクト指向プログラミング(OOP)をサポートしています。 2。C#の非同期プログラミングは非同期を通じて実装され、適用応答性を向上させるためにキーワードを待ちます。 3. LINQを使用してデータ収集を簡潔に処理します。 4.一般的なエラーには、null参照の例外と、範囲外の例外インデックスが含まれます。デバッグスキルには、デバッガーと例外処理の使用が含まれます。 5.パフォーマンスの最適化には、StringBuilderの使用と、不必要な梱包とボクシングの回避が含まれます。

テストC#.NETアプリケーション:ユニット、統合、およびエンドツーエンドテストテストC#.NETアプリケーション:ユニット、統合、およびエンドツーエンドテストApr 09, 2025 am 12:04 AM

C#.NETアプリケーションのテスト戦略には、ユニットテスト、統合テスト、エンドツーエンドテストが含まれます。 1.単位テストにより、コードの最小ユニットがMSTEST、ヌニット、またはXUNITフレームワークを使用して独立して動作することを保証します。 2。統合テストでは、一般的に使用されるシミュレートされたデータと外部サービスを組み合わせた複数のユニットの機能を検証します。 3.エンドツーエンドのテストでは、ユーザーの完全な操作プロセスをシミュレートし、通常、セレンは自動テストに使用されます。

高度なC#.NETチュートリアル:次のシニア開発者インタビューをエース高度なC#.NETチュートリアル:次のシニア開発者インタビューをエースApr 08, 2025 am 12:06 AM

C#シニア開発者とのインタビューでは、非同期プログラミング、LINQ、.NETフレームワークの内部作業原則などのコア知識をマスターする必要があります。 1.非同期プログラミングは、非同期を通じて操作を簡素化し、アプリケーションの応答性を向上させるのを待ちます。 2.LinqはSQLスタイルでデータを操作し、パフォーマンスに注意を払います。 3.ネットフレームワークのCLRはメモリを管理し、ガベージコレクションに注意して使用する必要があります。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強力な PHP 統合開発環境

PhpStorm Mac バージョン

PhpStorm Mac バージョン

最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

VSCode Windows 64 ビットのダウンロード

VSCode Windows 64 ビットのダウンロード

Microsoft によって発売された無料で強力な IDE エディター

Dreamweaver Mac版

Dreamweaver Mac版

ビジュアル Web 開発ツール