-8

我需要在 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 不起作用,我不明白为什么。如何解决?

4

2 回答 2

11

代替

int[] mas = new int[n];

mas = new int[n];

您想使用您的字段 - 现在您正在将构造函数中的数据分配给局部变量,这在ShowAll方法中不可用。

于 2013-07-08T13:10:24.397 回答
2

编辑:

删除构造函数中int[]定义的前缀int[] mas,它会创建一个局部变量,阻止您(难以找到)对所需字段的定义mas

编辑2: 正如我在评论中解释的那样,这是定义变量的方式,通过在构造函数内部而不是在类本身中这样做,您创建了一个局部变量,在完成构造函数的工作后不可用。

另一件需要注意的事情,最好在类的顶部定义字段/属性,这样可以避免寻找隐藏字段,例如此处的案例。

另外,你应该了解类变量和局部变量,我建议看看这里:

变量和参数

于 2013-07-08T13:09:47.377 回答