2014-02-07 18 views
3

我的錯誤: Field 'StockManagement.LargeItems1.largeS' is never assigned to, and will always have its default value null 我的代碼:字段「XXX」從未分配,並且將永遠有它的默認值空

namespace StockManagement 
{ 
    class LargeItems1 
    { 
     private Stack<string> largeS; 

     public LargeItems1() 
     { 
      Stack<string> largeS = new Stack<string>(); 
     } 
     public void LargeItemsAdd() 
     { 
      string usersInput2, tempValue; 
      int tempValueI = 0; 
      bool attempt = false;//, whichOne = false; 
      Console.WriteLine("Would you like to remove or add an item to the storage area \n Reply add OR remove"); 
      string usersInput = Console.ReadLine(); 
      usersInput = usersInput.ToLower(); 

      if (usersInput.Contains("remove")) 
      { 
       LargeItemsRemove(largeS); 
       return; 
      } 
      else if (usersInput.Contains("add")) 
      { 

       Console.WriteLine("Please input (numerically) how many IDs you'd like to add"); 
       tempValue = Console.ReadLine(); 
       attempt = int.TryParse(tempValue, out tempValueI); 
       while (!attempt) 
       { 
        Console.WriteLine("Please input (numerically) how many IDs you'd like to add, you did not input a numeric value last time"); 
        tempValue = Console.ReadLine(); 
        attempt = int.TryParse(tempValue, out tempValueI); 
       } 
       for (int i = 0; i < tempValueI; i++) 
       { 

        Console.WriteLine("Please input the ID's (one at a time) of the item you would like to add"); 
        usersInput2 = Console.ReadLine(); 
        if (largeS.Contains(usersInput2)) 
        { 
         Console.WriteLine("That ID has already been stored"); 
        } 
        else 
        { 
         largeS.Push(usersInput2); 
        } 
       } 
       foreach (var item in largeS) 
       { 
        Console.WriteLine("Current (large) item ID's: " + item); 
       } 
      } 

     } 
     public void LargeItemsRemove(Stack<string> largeS) 
     { 
      if (largeS.Contains(null)) 
      { 
       Console.WriteLine("No IDs stored"); 
      } 
      else 
      { 

       string popped = largeS.Pop(); 
       foreach (var item in largeS) 
       { 
        Console.WriteLine("Pop: " + item); 
       } 
       Console.WriteLine("Removed ID = " + popped); 
      } 
     } 

    } 
} 

我不明白怎麼我的值賦給實例。我會很感激任何可以提供的幫助!

+2

您需要將其定義爲_field_或_property_,而不是構造函數中的局部變量。 http://msdn.microsoft.com/en-us/library/ms173118.aspx編輯:一般類的更多信息:http://msdn.microsoft.com/en-us/library/x9afc042.aspx EDITx2:哎呀,錯過了它被宣佈爲一個領域的事實,我現在看到格式是固定的;謝謝Tim。 –

回答

10

更改您的構造函數初始化,而不是局部變量領域:

public LargeItems1() 
{ 
    this.largeS = new Stack<string>(); 
} 
3

你必須初始化你的領域largeS,使用this關鍵字,以這樣的方式

this.largeS = new Stack<string>(); 

this關鍵字用於引用類的當前實例。如果你使用:

Stack<string> largeS = new Stack<string>(); 

你只是初始化一個新的局部變量,與你的私人領域無關。

查看有關this關鍵字的MSDN文檔。

+1

很好的解釋!謝謝,我只是看MSDN上的這個關鍵字,你的解釋幫助我理解它:)。 – Zain

相關問題