1. 程式人生 > >MyList 泛型委托

MyList 泛型委托

namespace cti eric get esp activator reat instance func

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Tool
{
    ///where T : class  使用的泛型只能是類 ,刪除這句話,可以是任何類型
    public class MyList<T> : IEnumerable where T : class
    {
        
public T this[int index] { get { return Ts[index]; } } public int Count = 0; private T[] Ts = new T[4]; public int Add(T t) { if (Count == Ts.Length) { T[] Tstemp = new T[Ts.Length * 2]; for (int i = 0; i < Ts.Length; i++) { Tstemp[i]
= Ts[i]; } Ts = Tstemp; } Ts[Count] = t; Count++; return Count; } //public IEnumerator GetEnumerator() //{ // return Ts.GetEnumerator(); //} public IEnumerator GetEnumerator() {
for (int i = 0; i < Count; i++) { yield return Ts[i]; } } public delegate TResult MyFunc<in T, out TResult>(T arg); public IEnumerable<T> Where(MyFunc<T, bool> predicate) { for (int i = 0; i < Count; i++) { if (!predicate.Invoke(Ts[i])) { continue; } yield return Ts[i]; } } public T Find(MyFunc<T, bool> predicate) { for (int i = 0; i < Count; i++) { if (predicate.Invoke(Ts[i])) { return Ts[i]; } } return Activator.CreateInstance<T>(); } public bool RomveAt(int index) { try { for (int i = index; i <= Count - 1; i++) { Ts[i] = Ts[i + 1]; } Count--; return true; } catch (Exception) { throw; } } public void Insert(int index, T item) { if (Ts.Length == Count) { T[] Tstemp = new T[Ts.Length * 2]; for (int i = 0; i < Ts.Length; i++) { Tstemp[i] = Ts[i]; } Ts = Tstemp; } T temp = Ts[index]; for (int i = Count; i >= index; i--) { Ts[i + 1] = Ts[i]; } Ts[index] = item; Count++; } } }

MyList 泛型委托