C# 中 if 语句的变量作用域问题及解决方案
这段代码存在一个作用域问题,即在 if 语句中定义的变量 sqlstr 只能在 if 语句块中访问,而在 else 语句块中无法访问。
为了解决这个问题,可以在 if 语句块之前定义一个空字符串变量 sqlstr,然后在 if 语句块和 else 语句块中分别给它赋值。修改后的代码如下:
string sqlstr = '';
if (condition == null)
{
sqlstr = string.Format($'select {ProductionProductNum} from {ProductProductionRecorderTableMainName}{production} where {ProductionDate} >= '{StartTime}' and {ProductionDate} <= '{EndTime}' ');
}
else
{
sqlstr = string.Format($'select {ProductionProductNum} from {ProductProductionRecorderTableMainName}{production} where {ProductionDate} >= '{StartTime}' and {ProductionDate} <= '{EndTime}' and {ProductionCondition} = '{condition}' ');
}
DataTable dt = SqlConnector.GetDataTable(sqlstr);
此外,还需要注意将查询条件的值用单引号括起来,以便在 SQL 语句中正确解析。
原文地址: https://www.cveoy.top/t/topic/mNxM 著作权归作者所有。请勿转载和采集!