2011-07-21 59 views
0

我一直在获取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(); 
     } 
    } 
} 

回答

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>(); 
} 
+0

哇,你明白了。它现在像一阵微风。我把“(你好)(myHello [1])[1])”改为“myHello [1] [1]”,因为它给了我一些铸造错误。再次感谢! – Vikyboss

3

需要实现getset这里:

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

这仍然很好。这是一个功能(自动属性)在C#3.0中添加 – Chandu

+1

我明白,但它返回null,这说明OP描述什么......要么在构造函数中赋值给值或实现这个来映射get/set到其中一个已经定义字典... – Yahia

+0

你知道吗,你可以在这里* *东西*。提问者正在做一些不完全明显或明智的事情。 –

相关问题