有谁知道为什么我得到Null异常错误?

时间:2011-07-21 03:58:12

标签: c# class

我继续获得Null异常。我在程序中实例化了myHello,但它仍然给了我这个错误。提前谢谢。

class Hello
{
    public Dictionary<int, string> one;
    public Dictionary<int, ushort> two;
    public Dictionary<int, bool> three;

    public Hello()
    {
        this.one = new Dictionary<int, string>();
        this.two = new Dictionary<int, ushort>();
        this.three = new Dictionary<int, bool>();
    }

    public Dictionary<int, object> Values
    {
        get;
        set;
    }

    public object this[int index]
    {
        get
        {
            return this.Values[index];
        }
        set
        {
            this.Values[index] = value;
        }
    }
}




class Program
{
    public static void myfun(ref Hello hu)
    {
        hu[0] = "Hello";
        hu[1] = 25;
        hu[2] = true;
    }

    static void Main(string[] args)
    {
        try
        {
            //Program myprog = new Program();
            var myHello = new Hello[2];
            myHello[0] = new Hello();
            myHello[1] = new Hello();

            myHello[1][1] = 2;
            myfun(ref myHello[1]);
            Console.WriteLine("" + (Hello)(myHello[1])[1]);

            Console.ReadKey();
        }
        catch (NullReferenceException ex)
        {
            Console.WriteLine(ex.Message);
            Console.ReadKey();
        }
    }
}

2 个答案:

答案 0 :(得分:5)

Values永远不会分配默认值,我认为您在分配值之前尝试访问Values属性。

将构造函数更改为:

public Hello()
{
    this.one = new Dictionary<int, string>();
    this.two = new Dictionary<int, ushort>();
    this.three = new Dictionary<int, bool>();
    this.Values = new Dictionary<int, object>();
}

答案 1 :(得分:3)

您需要在此处实施getset

 public Dictionary<int, object> Values
    {
        get;
        set;
    }