2013-12-10 76 views
0

的錯誤是:CS0103: The name 'toAdresses' does not exist in the current context名稱「toAdresses」不在當前情況下存在

在下面的代碼:

public bool myFunction() 
    { 
     string toAddress; 

     toAddress = "[email protected],[email protected]";  // for testing 

     int firstCharacter = toAddress.IndexOf(','); 

     if (firstCharacter != -1) 
     { 
      string[] toAdresses = toAddress.Split(','); 
     } 
     else 
     { 
      string[] toAdresses = new string[]{toAddress}; 
     } 

     for (int i = 0; i < toAdresses.Length; i++)  // here is the error with toAdresses.Length 
     { 
      // do this 
     } 
    } 

感謝您的幫助!

+2

可怕的變量命名:( –

+0

如果你有興趣更多在編碼方面,Code Complete 2是一本很好的書,並討論了變量命名的重要性。如果你是一個剛開始學習的新開發人員,那麼這是帶有經驗的東西,沒有什麼會感到羞恥。 –

回答

7

你變量的範圍僅限於你定義它的塊。在這種情況下,toAddresses在你的if/else塊和失去範圍定義,當您退出該塊

配售。塊之外的變量定義將擴大它的範圍

例如:

string[] toAdresses; 
if (firstCharacter != -1) 
{ 
    toAdresses = toAddress.Split(','); 
} 
else 
{ 
    toAdresses = new string[]{toAddress}; 
} 
2

您已經在條件內定義了toAddresses數組。這意味着當你離開該塊時,變量不再在範圍內(即使在ifelse塊中都定義了它)

相反,應該在塊外部定義變量,並且只在塊內初始化變量:

string[] toAddresses; 

if(firstCharacter != -1) 
{ 
    toAddresses = toAddress.Split(','); 
} 
else 
{ 
    toAddresses = new string[] { toAddress }; 
} 
1

你需要移動toAdresses聲明中的if-else塊之外,或只是擺脫它:

public bool myFunction() 
{ 
    string toAddress; 

    toAddress = "[email protected],[email protected]";  // for testing 

    int firstCharacter = toAddress.IndexOf(','); 

    string[] toAdresses = firstCharacter != -1 
          ? toAddress.Split(',') 
          : new string[]{toAddress}; 

    for (int i = 0; i < toAdresses.Length; i++)  // here is the error with toAdresses.Length 
    { 
     // do this 
    } 
} 
相關問題