以字面方式定义数组和键 - C#

发布于 2024-11-17 16:21:26 字数 396 浏览 5 评论 0原文

试图将其合并

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

无畏 2024-11-24 16:21:26

听起来您实际上是在寻找 Dictionary 而不是传统的 C# 数组:

var dictionary = new Dictionary<int, string>
{
    { 0, "Index 0" },
    { 3, "Index 3" },
    { 4, "Index 4" }
};

It sounds like you're really after a Dictionary<int, string> rather than a traditional C# array:

var dictionary = new Dictionary<int, string>
{
    { 0, "Index 0" },
    { 3, "Index 3" },
    { 4, "Index 4" }
};
离不开的别离 2024-11-24 16:21:26

在 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.

离旧人 2024-11-24 16:21:26

据我所知,你不能跳过常规数组中的索引号(例如0,1,2,然后是4,没有3)。您需要使用不同的数据结构,例如字典或哈希表。

Hashtable ht = new Hashtable()
{
    {"key1", "value1"},
    {"key2", "value2"}
};

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.

Hashtable ht = new Hashtable()
{
    {"key1", "value1"},
    {"key2", "value2"}
};
浮云落日 2024-11-24 16:21:26

根据我的理解,你不能按照你想要的方式定义数组。其他海报表明您可以使用关联数组(字典)

最多您可以创建一个解决方法:


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";

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文