C#实现Ruby的负数索引器 C#实现Ruby的负数索引器

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C#实现Ruby的负数索引器 C#实现Ruby的负数索引器

  2021-03-22 我要评论
想了解C#实现Ruby的负数索引器的相关内容吗,在本文为您仔细讲解C#实现Ruby的负数索引器的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:c#中索引器的实现过程,索引器的实现过程,c#,索引器,下面大家一起来学习吧。

C#实现Ruby的负数索引器

public class InvertibleList<T> : List<T>
  {
    public new T this[int index]
    {
      get
      {
        if (index >= 0) return base[index];
        if (Count + index < 0)
          throw new IndexOutOfRangeException();
        return this[Count + index];
      }
      set
      {
        if (index >= 0)
          base[index] = value;
        else
        {
          if (Count + index < 0) 
            throw new IndexOutOfRangeException();
          this[Count + index] = value;
        }
      }
    }
    
  }

使用方法:

InvertibleList<string> list=new InvertibleList<string>
      {
        "1",
        "2",
        "3",
        "4",
        "5",
      };

      list[-2] = "asd";
      list.ForEach(Console.WriteLine);

代码很简单,使用也很方便,希望对大家学习C#能够有所帮助

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们