为什么bool的默认值val(false)无法识别?

时间:2014-04-23 16:31:42

标签: c# boolean default default-value

使用此代码:

bool successfulSend;
const string quote = "\"";
string keepPrinterOn = string.Format("! U1 setvar {0}power.dtr_power_off{0} {0}off{0}", quote);
string shutPrinterOff = string.Format("! U1 setvar {0}power.dtr_power_off{0} {0}on{0}", quote);
string advanceToBlackBar = string.Format("! U1 setvar {0}media.sense_mode{0} {0}bar{0}", quote);
string advanceToGap = string.Format("! U1 setvar {0}media.sense_mode{0} {0}gap{0}", quote);

if (radbtnBar.Checked)
{
    successfulSend = SendCommandToPrinter(advanceToBlackBar);
}
else if (radbtnGap.Checked)
{
    successfulSend = SendCommandToPrinter(advanceToGap);
}
if (successfulSend)
{
    MessageBox.Show("label type command successfully sent");
}

我明白," 使用未分配的本地变量' successfulSend' "

所以我必须将bool声明更改为:

bool successfulSend = false;

...让它编译/运行。但是,bool [ean]的默认值是不是假的?为什么必须明确指定默认值?

此代码没有任何投诉:

public bool SendCommandToPrinter(string cmd)
{
    bool success; // init'd to false by default
    try
    {
        SerialPort serialPort = new SerialPort();
        serialPort.BaudRate = 19200;
        serialPort.Handshake = Handshake.XOnXOff;
        serialPort.Open();
        serialPort.Write(cmd);
        serialPort.Close();
        success = true;
    }
    catch // may not need a try/catch block, as success defaults to false
    {
        success = false;
    }
    return success;
}

更新

编译:

bool success;
SerialPort serialPort = new SerialPort();
serialPort.BaudRate = 19200;
serialPort.Handshake = Handshake.XOnXOff;
serialPort.Open();
serialPort.Write(cmd);
serialPort.Close();
success = true;
return success;

1 个答案:

答案 0 :(得分:9)

  

但是不是bool [ean] s的默认值?

对于字段(实例变量和静态变量),是的。

但是局部变量不具有默认值,无论其类型如何。他们 在他们阅读之前必须明确分配。