C#通过索引引用数组元素不起作用 [英] C# referencing array element by index not working
问题描述
请帮助在C#中按索引访问数组元素。我有一系列我们提供的服务,我想点击某个按钮来累积每种服务的总数。我已经声明了一系列服务总计和一个累积总计的简单方法
这是我的代码的骨架:
Please help with accessing array element by index in C#. I have an array of services we offer and I want at the click of a button somewhere to accumulate totals per type of service. I have declared an array of service totals and a simple method to accumulate totals
Here is the skeleton of my code:
private int[] serviceTotals = new int[10];
public void AccumulateTotals()
int indexInteger=0;
int serviceCount +=1;
ServiceTotals[indexInteger]+=serviceCount;
问题是程序中的其他地方我称之为方法&使用此代码:
The problem is somewhere else in the program I call the the method & use this code:
AccummulateTotals()
Textbox1.Text = serviceTotals[0].ToString //for the first item in the array
我收到一个错误:无法将带有[]的索引应用于'int'类型的表达式
我做错了什么?
:调整后的代码标签
I get an error: "Cannot apply indexing with[] to an expression of type 'int'
What am I doing wrong??
: Adjusted code-tags
推荐答案
C#区分大小写。ServiceTotals
与serviceTotals
不同。
C# is case sensitive.ServiceTotals
is not the same asserviceTotals
.
试试这个:
Try this :
public int[] serviceTotals = new int[10];
填充数组:
to fill the array :
int serviceCount =1;
for (int i = 0; i < serviceTotals.Count(); i++)
{
serviceTotals[i] = serviceCount;
serviceCount++;
}
拨打第一项:
to call the first item :
MessageBox.Show(serviceTotals[0].ToString());
它必须有效,除非你指向不同类型的不同变量!区分大小写可能是问题。
it must work unless you're pointing to a different variable with different type! Case sensitivity may be the issue.
这篇关于C#通过索引引用数组元素不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!