2011-07-17 130 views
1

上次我有一個類似的問題,但我們想出瞭如果在邏輯語句之前初始化並設置變量的值,那麼我可以使用邏輯語句中生成的值。如何使用if語句中聲明的變量?

這次,我想根據連接字符串是否爲空來調用兩個方法重載中的一個。像這樣。

if (ConnectionString != "") // if there is something in the config file work with it 
{ 
    SqlConnection dataConnection = new SqlConnection(ConnectionString); 
} 
else 
{ 
    SqlConnection dataConnection = new SqlConnection(); 
} 

try { 
    // ... 

問題是try塊中的任何內容都會失敗,因爲它不知道dataConnection。

我該如何做到這一點,使其工作?

+3

如果您沒有連接字符串,您希望它來自哪裏?不要以爲SqlConnection會發明它,或者它會從天而降。你在'else'情況下做什麼?崩潰? –

+0

是連接字符串生成器在try塊中。 – Rob

+0

感謝大家的精彩答案!現在非常清楚。 – Rob

回答

3

聲明它(初始化)外:

SqlConnection conn; 
if(string.IsNullOrEmpty(connectionString)) { 
    conn = new SqlConnection(); 
} else { 
    conn = new SqlConnection(connectionString); 
} 

如果邏輯很簡單,一個條件也可能:

SqlConnection conn = string.IsNullOrEmpty(connectionString) 
    ? new SqlConnection() : new SqlConnection(connectionString); 

後者更易於與using塊一起使用,因爲它可以內聯完成。

6

你可以這樣說:

SqlConnection dataConnection = !string.IsNullOrEmpty(ConnectionString) 
    ? new SqlConnection(ConnectionString) : new SqlConnection(); 

或者:

SqlConnection dataConnection; 
if (string.IsNullOrEmpty(ConnectionString)) 
{ 
    dataConnection = new SqlConnection(ConnectionString); 
} 
else 
{ 
    dataConnection = new SqlConnection(); 
} 
1

你必須有,如果塊外的變量:

SqlConnection dataConnection; 
if (ConnectionString != "") // if there is something in the config file work with it 
{ 
    dataConnection = new SqlConnection(ConnectionString); 
} 
else 
{ 
    dataConnection = new SqlConnection(); 
} 
1

我想你應該之前定義的連接if語句

SqlConnection dataConnection = null; 
    if (ConnectionString != "") // if there is something in the config file work with it 
     { 
      dataConnection = new SqlConnection(ConnectionString); 
     } 
     else 
     { 
      dataConnection = new SqlConnection(); 
     } 
     try 
     { 
1

你可以,如果空值出方的聲明變量編號 然後在if語句中使用它 以及當你需要使用它時檢查它是否不爲空

SqlConnection dataConnection = null; 
if (ConnectionString != "") // if there is something in the config file work with it 
{ 
    dataConnection = new SqlConnection(ConnectionString); 
} 
else 
{ 
    dataConnection = new SqlConnection(); 
} 
try 
{ 
    if(dataConnection != null) 
     DoWhatYouWant(); 
}