我需要在 C# 中创建类 Massive,我尝试了这段代码,但它不能正常工作
using System;
namespace Massiv1
{
class Program
{
static void Main(string[] args)
{
Console.Write("n = ");
int n = Convert.ToInt32(Console.ReadLine());
Massiv mas = new Massiv(n);
mas.ShowAll();
Console.Write("i = ");
int i = Convert.ToInt32(Console.ReadLine());
mas.ShowElement(i);
Console.ReadLine();
}
}
class Massiv
{
public Massiv(int n)
{
int[] mas = new int[n];
Random rand = new Random();
for (int i = 0; i < mas.Length; ++i)
{
mas[i] = rand.Next(0, 10);
}
}
public void ShowAll()
{
foreach (var elem in mas)
{
Console.Write(elem + " ");
}
Console.WriteLine();
}
public void ShowElement(int index)
{
try
{
Console.WriteLine("index {0} mas{1} = ", index, mas[index]);
}
catch (NullReferenceException)
{
Console.WriteLine("Error!");
}
}
public int this[int index]
{
get { return mas[index]; }
set { mas[index] = value; }
}
private int[] mas;
}
}
我的方法 ShowAll 不起作用,我不明白为什么。如何解决?