如何从C#中的数组访问元素?
首先,定义并初始化数组-
int[] p = new int[3] {99, 92, 95};现在,显示数组元素-
for (j = 0; j < 3; j++ ) {
Console.WriteLine("Price of Product[{0}] = {1}", j, p[j]);
}要访问任何元素,只需像这样包含您想要的元素的索引-
p[2];
以上是访问第三个元素。
现在让我们看完整的代码-
示例
using System;
namespace Program {
class Demo {
static void Main(string[] args) {
int[] p = new int[3] {99, 92, 95};
int j;
for (j = 0; j < 3; j++ ) {
Console.WriteLine("Price of Product[{0}] = {1}", j, p[j]);
}
//访问
int e = p[2];
Console.WriteLine("产品3rd价格: "+e);
Console.ReadKey();
}
}
}