search
HomeBackend DevelopmentC#.Net TutorialCompilation of basic knowledge of C# Basic knowledge (17) ILiest interface - generics

Inserting a value type into ArrayList will trigger a boxing operation, and retrieving a value type requires unboxing, as follows

            ArrayList myArrayList = new ArrayList();

            myArrayList.Add(40);//装箱

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

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

This will cause performance consumption. As for the detailed explanation of packing, see the next article.
In order to solve these problems, C# has the IList interface that supports generics. Let’s look at the detailed code below. In fact, the structure is the same as IList, except that generics are added.

 /// <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();
        }

The above is the content of the basic knowledge of C# (17) ILiest interface - generics. For more related content, please pay attention to PHP Chinese Net (www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing C# .NET Applications: Unit, Integration, and End-to-End TestingTesting C# .NET Applications: Unit, Integration, and End-to-End TestingApr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewAdvanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewApr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

C# .NET Interview Questions & Answers: Level Up Your ExpertiseC# .NET Interview Questions & Answers: Level Up Your ExpertiseApr 07, 2025 am 12:01 AM

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.