3

我收到以下错误:

数组初始值设定项只能用于变量或字段初始值设定项。尝试改用新的表达式。

这是我的代码:

// Declare listbox information array
string [] tablet = new string[]{{"Microsoft Surface  Price: $1,162.99  Screen Size: 10.6 Inches  Storage Capacity: 128 GB"},

                                {"iPad 2 Price: $399.99, Screen Size: 9.7 Inches, Storage Capacity 16 GB"},
                                {"Samsung Galaxy Tab 2 Price: $329.99, Screen Size: 10.1 Inches, Storage Capacity 16 GB"},
                                {"NOOK HD Price: $199.99, Screen Size: 7 Inches, Storage Capacity 8 GB"},
                                {"IdeaTab Price: $149.99, Screen Size: 7 Inches, Storage Capacity: 8 GB"}};

//Array of product prices
int [] tabletPricesArray = new int[]{{"$1,162.99"},
                                       {"$399.99"},
                                       {"$329.99"},
                                       {"$199.99"},
                                       {"$149.99"}};

我不太确定出了什么问题。我对 C# 比较陌生。让我知道是否需要任何其他信息。

4

2 回答 2

5

几个问题:

问题1:

int在这里,您在提供字符串的同时创建一个类型数组。

  int [] tabletPricesArray = new int[]{"$1,162.99",
                                         "$399.99",
                                         "$329.99",
                                         "$199.99",
                                         "$149.99"};

问题2:

类型数组int不会保存浮点值,例如价格。而是使用float,doubledecimal(for $)。

    decimal[] tabletPricesArray = new decimal[]{1162.99M,
                                                 399.99M,
                                                 329.99M,
                                                 199.99M,
                                                 149.99M};

如果您只想tabletPricesArray用于将项目显示为字符串(无计算),那么您也可以在此处使用字符串数组。

问题3:

您不需要{ }在每个数组元素中。

于 2013-03-18T03:20:57.927 回答
4

我希望以下是您所期望的。我为你修改了代码。

       // Declare listbox information array
       string[] tablet = new string[]{"Microsoft Surface  Price: $1,162.99  Screen Size: 10.6 Inches  Storage Capacity: 128 GB",
                                      "iPad 2 Price: $399.99, Screen Size: 9.7 Inches, Storage Capacity 16 GB",
                                      "Samsung Galaxy Tab 2 Price: $329.99, Screen Size: 10.1 Inches, Storage Capacity 16 GB",
                                      "NOOK HD Price: $199.99, Screen Size: 7 Inches, Storage Capacity 8 GB",
                                      "IdeaTab Price: $149.99, Screen Size: 7 Inches, Storage Capacity: 8 GB"};

       // Array of product prices
       string[] tabletPricesArray = new string[]{"$1,162.99",
                                                   "$399.99",
                                                   "$329.99",
                                                   "$199.99",
                                                   "$149.99"};
于 2013-03-18T04:46:20.177 回答