2015-11-04 54 views
0

在我的项目中,我需要一个“移位”列表。 基本上我有一个public class dyn_int : List<int>来支持我们的一些旧脚本(写在一个专有的语言,但“半自动翻译”,以C#)覆盖索引运算符的偏移量

在这种语言,名单开始了他们的指数为1,而不是0!

我目前尝试创建一个方便的API,以便我们的开发人员仍然可以使用他们熟悉的风格。

但是我坚持创建索引运算符。 这是我目前对列表的索引访问器的实现。 吸气剂工作正常,但我不知道如何处理set方法。 到目前为止我没有找到List.SetElementAt(key, value)的方法。

public class dyn_int : List<int> 
{ 
    public int this[int key] 
    { 
     get 
     { 
      return this.ElementAt(key-1); 
     } 
    } 
} 
+1

'getter正常工作......你试过'dyn_int [0]'吗? – Jonesopolis

+5

我会*强烈*敦促你在这里使用组合而不是继承(并开始遵循.NET命名约定)。给你的班级一个'List '*变量*,而不是从'List '派生出来,并让你的班级实施'IList '......尽管考虑到索引者的期望,这将是“有趣的”。 –

+1

您也不应该使用'ElementAt'从列表中获取项目。您正在迭代整个序列以获取该节点。 – Servy

回答

1

这是一个快速的linqPad测试。你需要做一些错误处理等,但这应该让你去。

void Main() 
{ 
    var list = new CustomList<int>(); 
    list.Add(1); 
    list.Add(2); 

    list[1] = 5; 
    list[1].Dump(); //output 5 
} 

public class CustomList<T> 
{ 
    IList<T> list = new List<T>(); 

    public void Add(T item) 
    { 
     list.Add(item); 
    } 

    public T this[int index] 
    { 
     get 
     { 
      return list[index - 1]; 
     } 
     set 
     { 
      list[index - 1] = value; 
     } 
    } 
} 
+0

我已经试过这个解决方案(函数add)。但是,我正在寻找一种使用索引来直接设置元素的方法。 – stklik

+0

然后只需添加一个setter。我更新了答案。 –