C#实现Ruby的负数索引器
程序员文章站
2023-08-29 21:32:40
c#实现ruby的负数索引器
public class invertiblelist : list
{
pub...
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#能够有所帮助