如何为C#字符串数组元素添加自定义int/uint数值?
在C#中为字符串元素绑定自定义数值标识的实现方案
C#的普通数组必须使用从0开始的连续整数索引,无法直接为元素指定非连续或自定义的int/uint索引值,但可以通过以下几种替代方案实现类似需求:
方法1:使用Dictionary<TKey, TValue>
这是最直接的实现方式,用自定义的int/uint作为键,对应字符串作为值,完美匹配你的需求:
Dictionary<int, string> customIndexedItems = new Dictionary<int, string>() { { 15, "Item1" }, { 30, "Item2" }, { 45, "Item3" }, { 60, "Item4" }, { 75, "Item5" } }; // 按自定义索引访问元素 string targetItem = customIndexedItems[30]; // 获取"Item2"
- 支持自由设定任意int/uint类型的键,无连续要求
- 键不可重复,查找效率高
- 可以随时添加、删除键值对
方法2:自定义类封装
如果需要为元素附加更多属性(比如除了自定义索引外的其他信息),可以定义类来封装:
public class IndexedStringItem { public uint CustomId { get; set; } public string Value { get; set; } } // 初始化数据 List<IndexedStringItem> items = new List<IndexedStringItem>() { new IndexedStringItem { CustomId = 1001, Value = "Item1" }, new IndexedStringItem { CustomId = 2002, Value = "Item2" }, new IndexedStringItem { CustomId = 3003, Value = "Item3" } }; // 根据自定义ID查找元素 var matchedItem = items.FirstOrDefault(x => x.CustomId == 2002); if (matchedItem != null) { string result = matchedItem.Value; // 获取"Item2" }
- 扩展性强,可随时添加额外属性
- 支持重复的自定义ID(如果业务需要)
方法3:枚举+数组(固定索引场景)
如果自定义索引是固定的业务标识,可用枚举映射索引值,再结合数组使用:
public enum CustomItemIndex { FirstItem = 5, SecondItem = 15, ThirdItem = 25, FourthItem = 35, FifthItem = 45 } // 注意:数组长度需大于等于最大枚举值+1,避免索引越界 string[] items = new string[(int)CustomItemIndex.FifthItem + 1]; items[(int)CustomItemIndex.FirstItem] = "Item1"; items[(int)CustomItemIndex.SecondItem] = "Item2"; // 通过枚举访问元素 string target = items[(int)CustomItemIndex.FirstItem];
- 代码可读性高,适合索引值固定且有业务含义的场景
- 缺点:如果索引值跨度大,会造成数组内存浪费
内容的提问来源于stack exchange,提问作者user19750905
相关产品推荐
相关产品推荐

