如何使用if语句中声明的变量
本文关键字:声明 变量 语句 何使用 if | 更新日期: 2023-09-27 18:02:25
上次我有一个类似的问题,但是我们发现如果在逻辑语句之前为变量初始化并设置一个值,那么我可以使用逻辑语句中生成的值。
这一次,我想根据连接字符串是否为空调用两个方法重载中的一个。一样。
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。
我怎么做才能使它工作?
你可以这样做:
SqlConnection dataConnection = !string.IsNullOrEmpty(ConnectionString)
? new SqlConnection(ConnectionString) : new SqlConnection();
或:
SqlConnection dataConnection;
if (string.IsNullOrEmpty(ConnectionString))
{
dataConnection = new SqlConnection(ConnectionString);
}
else
{
dataConnection = new SqlConnection();
}
在外部声明它(未初始化):
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
块,因为它可以内联完成。
你必须将变量置于if块之外:
SqlConnection dataConnection;
if (ConnectionString != "") // if there is something in the config file work with it
{
dataConnection = new SqlConnection(ConnectionString);
}
else
{
dataConnection = new SqlConnection();
}
我认为你应该在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语句外声明null值的变量然后在if语句中使用它当你需要使用它时检查它是否为null
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();
}