如何初始化指定所需索引的数组常量

发布于 2024-09-15 15:47:13 字数 232 浏览 7 评论 0原文

我只想通过指定值以及它们将附加到的索引来初始化 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 技术交流群。

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

发布评论

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

评论(6

一人独醉 2024-09-22 15:47:15

我认为在 C# 中声明数组时不可能实现您想要的。

除了像其他人建议的那样使用 Dictionary 之外,您还可以尝试使用枚举,其中的值对应于您的特定数组索引和对应于的描述(使用 Description 属性)字符串值。

private enum Pets
{
   [Description("GreyHound")]
   Greyhound = 5,
   [Description("Bulldog")]
   Bulldog = 29
}

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 the Description attribute) corresponding to the string values.

private enum Pets
{
   [Description("GreyHound")]
   Greyhound = 5,
   [Description("Bulldog")]
   Bulldog = 29
}
终遇你 2024-09-22 15:47:15

作为记录,我同意每个人的观点,字典可能更合适。但是您可以编写一个小方法来实现您想要的:

public static T[] CreateArray<T>(params Tuple<int, T>[] values)
{
    var sortedValues = values.OrderBy(t => t.Item1);

    T[] array = new T[sortedValues.Last().Item1 + 1];

    foreach(var value in sortedValues)
    {
        array[value.Item1] = value.Item2;
    }

    return array;
}

并像这样调用它:

string[] myArray = CreateArray(new Tuple<int, string>(34, "cat"), new Tuple<int, string>(12, "dog"));

如果 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:

public static T[] CreateArray<T>(params Tuple<int, T>[] values)
{
    var sortedValues = values.OrderBy(t => t.Item1);

    T[] array = new T[sortedValues.Last().Item1 + 1];

    foreach(var value in sortedValues)
    {
        array[value.Item1] = value.Item2;
    }

    return array;
}

And call it like this:

string[] myArray = CreateArray(new Tuple<int, string>(34, "cat"), new Tuple<int, string>(12, "dog"));

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.

拒绝两难 2024-09-22 15:47:15

您不能在初始化程序中执行此操作,您需要首先指定数组的大小,然后在特定位置添加项目。

private static readonly string[] Pets = new string[42];

然后在静态构造函数中插入项目。

private static MyClass
{
    Pets[29] = "Bulldog";
    Pets[5] = "Greyhound";
}

但正如其他人所建议的:使用 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.

private static readonly string[] Pets = new string[42];

and then in a static constructor you insert your items.

private static MyClass
{
    Pets[29] = "Bulldog";
    Pets[5] = "Greyhound";
}

But as other have suggested: use the Dictionary<int, string>.

苹果你个爱泡泡 2024-09-22 15:47:15

您不需要字符串数组,而是需要一个Dictionary

看一下 链接文本,那里有一个很好的示例(我在这里进行了改编):

Dictionary<int, string> d = new Dictionary<int, string>();
        d.Add(2, "cat");
        d.Add(1, "dog");
        d.Add(0, "llama");
        d.Add(-1, "iguana");

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<int, string> d = new Dictionary<int, string>();
        d.Add(2, "cat");
        d.Add(1, "dog");
        d.Add(0, "llama");
        d.Add(-1, "iguana");
不美如何 2024-09-22 15:47:14

如果您的数据结构具有一定的灵活性,则使用 Dictionary 而不是数组来实现此行为会更有效。

示例(如果您使用 C# 3 或更高版本):

var pets = new Dictionary<int, string> {
    { 29, "Bulldog" },
    { 5, "Greyhound" }
};
Console.WriteLine(pets[5]);

旧应用程序的相同示例:

Dictionary<int, string> pets = new Dictionary<int, string>();
pets[29] = "Bulldog";
pets[5] = "Greyhound";
Console.WriteLine(pets[5]);

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):

var pets = new Dictionary<int, string> {
    { 29, "Bulldog" },
    { 5, "Greyhound" }
};
Console.WriteLine(pets[5]);

Same example for legacy applications:

Dictionary<int, string> pets = new Dictionary<int, string>();
pets[29] = "Bulldog";
pets[5] = "Greyhound";
Console.WriteLine(pets[5]);
江湖彼岸 2024-09-22 15:47:14

听起来你不需要一个数组,而是一个 Dictionary ,它可以像这样初始化:(

private static readonly Dictionary<int, string> pets = 
    new Dictionary<int, string> {
    { 29, "Bulldog" },
    { 5, "Greyhound" }
};

请注意,这个集合初始化器语法是仅在 C# 3 中添加。如果您使用旧版本,则必须多次显式调用 Add 或索引器。)

您可以通过索引器访问字典 看起来像数组访问:

string x = pets[29];
pets[10] = "Goldfish";

It sounds like you don't want an array, but a Dictionary<int, string> instead, which could be initialized like this:

private static readonly Dictionary<int, string> pets = 
    new Dictionary<int, string> {
    { 29, "Bulldog" },
    { 5, "Greyhound" }
};

(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:

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