首页 > Windows开发 > 详细

C#实现Ruby的负数索引器

时间:2016-07-31 06:53:06      阅读:346      评论:0      收藏:0      [点我收藏+]
    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#实现Ruby的负数索引器

原文:http://www.cnblogs.com/juking52/p/5722266.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!