如何初始化指定所需索引的数组常量
我只想通过指定值以及它们将附加到的索引来初始化 string[] 数组常量。
例如,在:
private static readonly string[] Pets = new string[] {"Bulldog", "GreyHound"};
我想说 BullDog 对应索引 29,GreyHound 对应索引 5(就像 php :) )
有什么建议吗?
干杯,
What I just want is to initialize a string[] array constant by specifying not only the values, but the indexes they will be attached to.
For example, on:
private static readonly string[] Pets = new string[] {"Bulldog", "GreyHound"};
I would like to state that BullDog corresponds to index 29 and GreyHound to 5 (Like php :) )
Any suggestion?
Cheers,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我认为在 C# 中声明数组时不可能实现您想要的。
除了像其他人建议的那样使用
Dictionary
之外,您还可以尝试使用枚举,其中的值对应于您的特定数组索引和对应于的描述(使用Description
属性)字符串值。I don't think what you want is possible in C# when declaring arrays.
Besides using a
Dictionary
as others have suggested, you could try using an enumeration instead, with values corresponding to your specific array indices and descriptions (using theDescription
attribute) corresponding to the string values.作为记录,我同意每个人的观点,
字典
可能更合适。但是您可以编写一个小方法来实现您想要的:并像这样调用它:
如果 C# 收到许多人似乎想要的
Tuple
语法糖,这看起来会更干净一点。这是个好主意吗?几乎肯定不会,但我将把它留给OP来判断。
For the record, I agree with everyone that a
Dictionary
is probably more appropriate. But you can write a little method to pull off what you want:And call it like this:
If C# receives the syntactic sugar for
Tuple
that many people seem to want, this would get a tad cleaner looking.Is this a good idea? Almost certainly not, but I'll leave that for the OP to judge.
您不能在初始化程序中执行此操作,您需要首先指定数组的大小,然后在特定位置添加项目。
然后在静态构造函数中插入项目。
但正如其他人所建议的:使用
Dictionary
。You can not do that in the initializer, you need to first specify the size of the array and then add items at specific locations.
and then in a static constructor you insert your items.
But as other have suggested: use the
Dictionary<int, string>
.您不需要字符串数组,而是需要一个
Dictionary
。看一下 链接文本,那里有一个很好的示例(我在这里进行了改编):
You don't need a string array, but instead a
Dictionary
.Take a look at link text, there's a fine example there (which I adapted here):
如果您的数据结构具有一定的灵活性,则使用
Dictionary
而不是数组来实现此行为会更有效。示例(如果您使用 C# 3 或更高版本):
旧应用程序的相同示例:
If you have some flexibility in terms of your data structure, it would be more efficient to use a
Dictionary<int, string>
instead of an array for this behavior.Example (if you are using C# 3 or above):
Same example for legacy applications:
听起来你不需要一个数组,而是一个
Dictionary
,它可以像这样初始化:(请注意,这个集合初始化器语法是仅在 C# 3 中添加。如果您使用旧版本,则必须多次显式调用
Add
或索引器。)您可以通过索引器访问字典 看起来像数组访问:
It sounds like you don't want an array, but a
Dictionary<int, string>
instead, which could be initialized like this:(Note that this collection initializer syntax was only added in C# 3. If you're using an older version you'll have to call
Add
or the indexer explicitly multiple times.)You can access a dictionary via its indexer which looks like array access: