用于数组访问的硬编码索引
本文关键字:编码 索引 数组 访问 用于 | 更新日期: 2023-09-27 18:00:32
我有一个数组,其中包含按特定顺序排列的数据。为了不太乱,我通常对索引进行硬编码:
public class MyClass
{
private readonly string[] data = new string[DATA_LENGHT];
internal const INDEX_NAME = 00;
internal const INDEX_FIRSTNAME = 01;
internal const INDEX_CITY = 02;
...
internal const DATA_LENGHT = XX;
}
但这种方式是为了维持生计。如果我想插入一个新的数据,比如在索引0处,我需要手动更改所有后续的index-XXX。
我想使用某种初始化器,但以下不起作用:
internal const INDEX_NAME = i++;
internal const INDEX_FIRSTNAME = i++;
internal const INDEX_CITY = i++;
我也可以将const更改为只读,并在静态构造函数中初始化它,但这意味着每个INDEX有两行用于初始化(实际上看起来不太好)。
什么是干净、简单的方法呢?
最好的答案可能是像Blorgbeard建议的那样使用enum
。
enum Indices : int
{
Name = 0,
FirstName,
City,
//...
Length
}
另一种解决方案是增加以前的值。
internal const int INDEX_NAME = 0;
internal const int INDEX_FIRSTNAME = INDEX_NAME + 1;
internal const int INDEX_CITY = INDEX_FIRSTNAME + 1;
您还可以使用Dictionary来保存索引值。这将使您回到每个索引一行,再加上Dictionary init的几个额外行。
private Dictionary<string,string> _indexDictionary;
public MyClass()
{
_indexDictionary = new Dictionary<string,string>();
_indexDictionary.Add("INDEX_NAME","00");
_indexDictionary.Add("INDEX_FIRSTNAME","01");
...
}
然后你只需要从字典中提取索引值:
var blah = data[_indexDictionary["INDEX_NAME"]]
可读性权衡是有争议的,比枚举的开销大一点,但有效。。。
尝试为此使用枚举:
public enum MyIndexes
{
INDEX_NAME = 0,
INDEX_FIRSTNAME,
INDEX_FIRSTNAME
}
您可以为每个条目声明一个值,也可以声明第一个值。如果你这样做,所有的东西都会增加一。当你想在数组中使用它作为索引时,你可以使用以下方法:
(int)MyIndexes.INDEX_NAME // index 0
(int)MyIndexes.INDEX_FIRSTNAME // would be index 1
您的方法很奇怪,但您可以用枚举替换常量,例如:
public enum Indices
{
INDEX_NAME = 0,
INDEX_FIRSTNAME,
INDEX_CITY,
...
}
然后
data[(int)Indices.INDEX_NAME]