开关语句中的 C# 变量作用域
本文关键字:变量 作用域 语句 开关 | 更新日期: 2023-09-27 18:32:03
我有一个以这个开头的函数:
void RecordLoadPosition()
{
OdbcCommand command;
if (_hasPlantGenie)
{
command = new OdbcCommand();
string query;
switch (ItemType)
{
case ItemTypeEnum.COIL:
// We're only going to add records to the coils_pg table when the coil gets moved. After
// a record is added, we'll update it.
command = new OdbcCommand("select * from coils_pg where coil_id = " + _itemName, _db);
当我编译它时,我在 if 块的第一行没有收到错误,但我收到错误,抱怨在案例块内声明之前我无法使用"命令"。 我不明白为什么函数顶部的声明在案例块中不可用。
不过还好。 如果它在案例块中不可见,我可以声明它。 我将案例块中的第一个语句更改为"OdbcCommand command..."。 现在我收到一个错误,抱怨我无法声明已经在父块中声明的变量! 无论哪种方式,我都赢不了!
这是怎么回事?
当然,我只能使用不同的 OdbcCommand 对象,这就是我现在要做的,但我想了解这一点。
====
================================================我的原始代码示例中似乎确实缺少某些内容,但我不知道是什么。 这是一个小函数,它应该显示相同的错误,但没有:
void ScopeTest()
{
OdbcCommand command = null;
if (_hasPlantGenie)
{
command = new OdbcCommand();
switch (ItemType)
{
case ItemTypeEnum.COIL:
// We're only going to add records to the coils_pg table when the coil gets moved. After
// a record is added, we'll update it.
command = new OdbcCommand();
break;
}
}
}
====
===================================================而且,因为人们要求它,这里是完整的原始函数(包括在 if 块顶部额外创建一个 OdbcCommand 对象,只是为了证明它不会抛出错误:
void RecordLoadPosition()
{
OdbcCommand command = null;
if (_hasPlantGenie)
{
command = new OdbcCommand();
string query;
switch (ItemType)
{
case ItemTypeEnum.COIL:
// We're only going to add records to the coils_pg table when the coil gets moved. After
// a record is added, we'll update it.
command = new OdbcCommand("select * from coils_pg where coil_id = " + _itemName, _db);
OdbcDataReader reader = command.ExecuteReader();
if (reader.Read())
{
query = "update plant_genie.coils_pg set x_coordinate = " +
XPosCurrent.ToString() +
", y_coordinate = " +
YPosCurrent.ToString() +
" where coil_id = '" +
_itemName + "'";
reader.Close();
command.CommandText = query;
command.ExecuteNonQuery();
}
else
{
query = "insert into plant_genie.coils_pg(coil_id, x_coordinate, y_coordinate) values (" +
XPosCurrent.ToString() + YPosCurrent.ToString() +
"'" + _itemName + "')";
reader.Close();
command.CommandText = query;
command.ExecuteNonQuery();
}
break;
case ItemTypeEnum.INNER_COVER:
// The inner_cover_pg table will be pre-built. We can assume that it has records for
// each inner cover.
query = "select set_inner_cover_down(" +
XPosCurrent.ToString() +
", " +
YPosCurrent.ToString() +
", '" +
_itemName +
"')";
OdbcCommand command = new OdbcCommand(query, _db);
command.ExecuteNonQuery();
// See if the cover has been set down in a storage location. If it has
break;
}
}
}
在您的case ItemTypeEnum.INNER_COVER:
状况中,您有:
OdbcCommand command = new OdbcCommand(query, _db);
您正在重新声明它,而您应该像在case ItemTypeEnum.COIL:
分支中一样分配它。将该行替换为:
command = new OdbcCommand(query, _db);