찾다
백엔드 개발C#.Net 튜토리얼C# 기본 지식 정리 기본 지식(17) ILiest 인터페이스 - 제네릭

ArrayList에 값 유형을 삽입하면 boxing 작업이 트리거되고 값 유형을 검색하려면

            ArrayList myArrayList = new ArrayList();

            myArrayList.Add(40);//装箱

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

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

와 같이 unboxing이 필요하므로 성능 소모가 발생합니다. 포장에 대한 자세한 설명은 다음 글을 참고하세요.
이러한 문제를 해결하기 위해 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);
        }
    }

전화:

 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 인터페이스 - Generics에 대한 자세한 내용은 주의하시기 바랍니다. PHP 중국어 넷(www.php.cn)!


성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
C# .NET로 개발 : 실용적인 가이드 및 예제C# .NET로 개발 : 실용적인 가이드 및 예제May 12, 2025 am 12:16 AM

C# 및 .NET은 강력한 기능과 효율적인 개발 환경을 제공합니다. 1) C#은 C의 힘과 Java의 단순성을 결합한 최신 객체 지향 프로그래밍 언어입니다. 2) .NET 프레임 워크는 여러 프로그래밍 언어를 지원하는 응용 프로그램을 구축하고 실행하는 플랫폼입니다. 3) C#의 클래스와 객체는 객체 지향 프로그래밍의 핵심입니다. 클래스는 데이터와 동작을 정의하고 객체는 클래스의 사례입니다. 4) .NET의 쓰레기 수집 메커니즘은 자동으로 메모리를 관리하여 개발자의 작업을 단순화합니다. 5) C# 및 .NET은 강력한 파일 작업 기능을 제공하여 동기 및 비동기 프로그래밍을 지원합니다. 6) 디버거, 로깅 및 예외 처리를 통해 일반적인 오류를 해결할 수 있습니다. 7) 성능 최적화 및 모범 사례에는 StringBuild 사용이 포함됩니다

C# .NET : Microsoft .NET 프레임 워크 이해C# .NET : Microsoft .NET 프레임 워크 이해May 11, 2025 am 12:17 AM

.NETFRAMEWORK는 일관된 프로그래밍 모델과 강력한 런타임 환경을 제공하는 교차 문자 크로스 플랫폼 개발 플랫폼입니다. 1) CLR 및 FCL로 구성되어 메모리와 스레드를 관리하고 FCL은 사전 제작 된 기능을 제공합니다. 2) 사용의 예로는 파일 읽기 및 LINQ 쿼리가 포함됩니다. 3) 일반적인 오류에는 처리되지 않은 예외와 메모리 누출이 포함되며 디버깅 도구를 사용하여 해결해야합니다. 4) 비동기 프로그래밍 및 캐싱을 통해 성능 최적화를 달성 할 수 있으며 코드 가독성 및 유지 관리 가능성을 유지하는 것이 중요합니다.

C# .net의 수명 : 지속적인 인기에 대한 이유C# .net의 수명 : 지속적인 인기에 대한 이유May 10, 2025 am 12:12 AM

C#.NET이 지속적으로 매력적으로 유지되는 이유는 우수한 성능, 풍부한 생태계, 강력한 지역 사회 지원 및 크로스 플랫폼 개발 기능을 포함합니다. 1) 탁월한 성능과 엔터프라이즈 수준의 응용 프로그램 및 게임 개발에 적합합니다. 2) .NET 프레임 워크는 다양한 개발 분야를 지원하기위한 광범위한 클래스 라이브러리 및 도구를 제공합니다. 3) 활발한 개발자 커뮤니티와 풍부한 학습 리소스가 있습니다. 4) .netCore는 크로스 플랫폼 개발을 실현하고 응용 프로그램 시나리오를 확장합니다.

C# .NET 디자인 패턴 마스터 링 : 싱글 톤에서 종속성 주입까지C# .NET 디자인 패턴 마스터 링 : 싱글 톤에서 종속성 주입까지May 09, 2025 am 12:15 AM

C#.NET의 설계 패턴에는 싱글 톤 패턴 및 종속성 주입이 포함됩니다. 1. Singleton Mode는 클래스의 인스턴스가 하나 뿐이며 글로벌 액세스 포인트가 필요한 시나리오에 적합하지만 스레드 안전 및 남용 문제에주의를 기울여야합니다. 2. 종속성 주입은 종속성을 주입하여 코드 유연성과 테스트 가능성을 향상시킵니다. 그것은 종종 생성자 주입에 사용되지만 복잡성을 증가시키기 위해 과도한 사용을 피해야합니다.

현대 세계의 C# .net : 응용 및 산업현대 세계의 C# .net : 응용 및 산업May 08, 2025 am 12:08 AM

C#.net은 현대 세계에서 게임 개발, 금융 서비스, 사물 인터넷 및 클라우드 컴퓨팅 분야에서 널리 사용됩니다. 1) 게임 개발에서 C#을 사용하여 Unity 엔진을 통해 프로그래밍하십시오. 2) 금융 서비스 분야에서 C#.NET은 고성능 거래 시스템 및 데이터 분석 도구를 개발하는 데 사용됩니다. 3) IoT 및 클라우드 컴퓨팅 측면에서 C#.NET은 Azure 서비스를 통해 지원을 제공하여 장치 제어 로직 및 데이터 처리를 개발합니다.

C# .NET 프레임 워크 대 .NET Core/5/6 : 차이점은 무엇입니까?C# .NET 프레임 워크 대 .NET Core/5/6 : 차이점은 무엇입니까?May 07, 2025 am 12:06 AM

.NETFRAMEWORKISWINDOWS 중심, while.netCore/5/6 SupportScross-PlatformDevelopment.1) .NETFramework, 2002 년 이후, isidealforwindowsapplicationsButlimitedIncross-platformcapabilities.2) .netcore, 2016, anditsevolutions (.net5/6).

C# .NET 개발자 커뮤니티 : 리소스 및 지원C# .NET 개발자 커뮤니티 : 리소스 및 지원May 06, 2025 am 12:11 AM

C#.NET 개발자 커뮤니티는 다음을 포함하여 풍부한 리소스와 지원을 제공합니다. 1. Microsoft의 공식 문서, 2. StackoverFlow 및 Reddit과 같은 커뮤니티 포럼, 3. GitHub의 오픈 소스 프로젝트. 이러한 리소스는 개발자가 기본 학습에서 고급 응용 프로그램에 이르기까지 프로그래밍 기술을 향상시키는 데 도움이됩니다.

C# .NET 장점 : 기능, 이점 및 사용 사례C# .NET 장점 : 기능, 이점 및 사용 사례May 05, 2025 am 12:01 AM

C#.net의 장점은 다음과 같습니다. 1) 비동기 프로그래밍과 같은 언어 기능은 개발을 단순화합니다. 2) JIT 컴파일 및 쓰레기 수집 메커니즘을 통한 효율성 향상, 성능 및 신뢰성; 3) 크로스 플랫폼 지원, .netcore는 응용 프로그램 시나리오를 확장합니다. 4) 웹에서 데스크탑 및 게임 개발에 이르기까지 뛰어난 성능을 가진 광범위한 실제 응용 프로그램.

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 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구