2011-07-21 61 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

你知道嗎,你可以在這裏* *東西*。提問者正在做一些不完全明顯或明智的事情。 –

相關問題