The name 'port' does not exist in the current context - C#
Формулировка задачи:
Всем привет!
Изучаю С# 4 час и столкнулся с проблемой которой озаглавлена тема.
как я понимаю компилятор не видет объекта, но вот по какой причине и как исправить понять не могу..
Ругается на port.Close();
По сути это должен быть обработчик кнопки который либо устанавливает соединение по ком порту либо разрывает его.
private void connect_Click(object sender, EventArgs e)
{
if (conect == false)
{
SerialPort port = new SerialPort(comNumber.Text, 9600, Parity.None, 8, StopBits.One);
port.Open();
connect.Text = "Отключить";
onOffConect.Text = "ON";
conect = true;
}
else
{
onOffConect.Text = "OFF";
port.Close();
}
}Решение задачи: «The name 'port' does not exist in the current context»
textual
Листинг программы
private void connect_Click(object sender, EventArgs e)
{
SerialPort port = null;
if (conect == false)
{
port = new SerialPort(comNumber.Text, 9600, Parity.None, 8, StopBits.One);
port.Open();
connect.Text = "Отключить";
onOffConect.Text = "ON";
conect = true;
}
else
{
onOffConect.Text = "OFF";
if (port != null)
port.Close();
}
}