以字面方式定义数组和键 - C#
试图将其合并
string[] array = new string[];
array[0] = "Index 0";
array[3] = "Index 3";
array[4] = "index 4";
到一行中...
PHP 中的示例
$array = array( 0 => "Index 0", 3 => "Index 3", 4 => "Index 4" );
我知道我可以做到这一点
string[] array = { "string1", "string2", "string3" }
但是我如何在那里获得正确的索引?
Trying to consolidate this...
string[] array = new string[];
array[0] = "Index 0";
array[3] = "Index 3";
array[4] = "index 4";
Into one line...
Example in PHP
$array = array( 0 => "Index 0", 3 => "Index 3", 4 => "Index 4" );
I know I can do this
string[] array = { "string1", "string2", "string3" }
But how would i get the proper indexes in there?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
听起来您实际上是在寻找
Dictionary
而不是传统的 C# 数组:It sounds like you're really after a
Dictionary<int, string>
rather than a traditional C# array:在 C# 中你不能。如果您想要特定的索引,则必须传入
null
值来保存空对象的位置。听起来您实际上是在寻找
Dictionary
。In C# you can't. If you wanted specific indexes you'd have to pass in
null
values to hold the place of the empty object.It sounds like you're really after a
Dictionary<TKey, TValue>
instead.据我所知,你不能跳过常规数组中的索引号(例如0,1,2,然后是4,没有3)。您需要使用不同的数据结构,例如字典或哈希表。
As far I know, you can't skip index numbers in regular array (e.g. 0,1,2 and then 4 without 3). You need to use different data structure like Dictionary or Hashtable.
根据我的理解,你不能按照你想要的方式定义数组。其他海报表明您可以使用关联数组(字典)
最多您可以创建一个解决方法:
string[] array = {"array0", "", "array2", "array3"};
或
<代码>
字符串[]数组=新字符串[4];
数组[0] = "数组0";
数组[2] = "数组2";
From my understanding you cannot define arrays in the way you want. Other posters have indicated you can use associative arrays (Dictionaries)
At best you can create a workaround:
string[] array = {"array0", "", "array2", "array3"};
or
string[] array = new string[4];
array[0] = "array0";
array[2] = "array2";