2011-07-17 75 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(); 
}