我收到以下错误:
数组初始值设定项只能在变量或字段初始值设定项中使用。请尝试使用新表达式。
这是我的代码:
// 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#比较陌生。如果需要任何其他信息,请与我们联系。
答案 0 :(得分:5)
有几个问题:
问题1:
在这里,您在创建一个类型int
的数组,同时提供字符串。
int [] tabletPricesArray = new int[]{"$1,162.99",
"$399.99",
"$329.99",
"$199.99",
"$149.99"};
问题2:
类型为int
的数组不会保存浮点值,例如价格。而是使用float
,double
或decimal
(对于$)。
decimal[] tabletPricesArray = new decimal[]{1162.99M,
399.99M,
329.99M,
199.99M,
149.99M};
如果您希望tabletPricesArray
仅用于将项目显示为字符串(无计算),那么您也可以在此处使用字符串数组。
问题3:
每个数组元素中不需要{ }
。
答案 1 :(得分:2)
我希望以下是你所期待的。我为你修改了代码。
// 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"};