欢迎光临散文网 会员登陆 & 注册

C#编程-第二季-面向对象-宇宙最简单2021最新版

2023-08-10 15:21 作者:雾隐半山  | 我要投稿

using System;


class MyList<T>

{

  private T[] items;

  private int count;


  public MyList()

  {

    items = new T[4];

    count = 0;

  }


  public int Capacity => items.Length;


  public int Count => count;


  public T this[int index]

  {

    get

    {

      if (index < 0 || index >= count)

      {

        throw new IndexOutOfRangeException();

      }

      return items[index];

    }

    set

    {

      if (index < 0 || index >= count)

      {

        throw new IndexOutOfRangeException();

      }

      items[index] = value;

    }

  }


  public void Add(T item)

  {

    if (count == items.Length)

    {

      ResizeArray();

    }

    items[count] = item;

    count++;

  }


  public void Insert(int index, T item)

  {

    if (index < 0 || index > count)

    {

      throw new IndexOutOfRangeException();

    }

    if (count == items.Length)

    {

      ResizeArray();

    }

    for (int i = count; i > index; i--)

    {

      items[i] = items[i - 1];

    }

    items[index] = item;

    count++;

  }


  public void RemoveAt(int index)

  {

    if (index < 0 || index >= count)

    {

      throw new IndexOutOfRangeException();

    }

    for (int i = index; i < count - 1; i++)

    {

      items[i] = items[i + 1];

    }

    count--;

    items[count] = default(T);

  }


  public int IndexOf(T item)

  {

    for (int i = 0; i < count; i++)

    {

      if (items[i].Equals(item))

      {

        return i;

      }

    }

    return -1;

  }


  public int LastIndexOf(T item)

  {

    for (int i = count - 1; i >= 0; i--)

    {

      if (items[i].Equals(item))

      {

        return i;

      }

    }

    return -1;

  }


  public void Sort()

  {

    Array.Sort(items, 0, count);

  }


  private void ResizeArray()

  {

    int newCapacity = items.Length * 2;

    T[] newArray = new T[newCapacity];

    Array.Copy(items, newArray, count);

    items = newArray;

  }

}


C#编程-第二季-面向对象-宇宙最简单2021最新版的评论 (共 条)

分享到微博请遵守国家法律