我使用以下代码检查空文本框,如果它为null,则跳过副本到剪贴板并转到其余代码.
我不明白为什么我得到一个"值不能为NULL"的例外.它不应该看到null并继续前进而不复制到剪贴板?
private void button_Click(object sender, EventArgs e)
{
if (textBox_Results.Text != null) Clipboard.SetText(textBox_Results.Text);
//rest of the code goes here;
}
Run Code Online (Sandbox Code Playgroud)
如果使用.NET 4 String.IsNullOrWhitespace()来检查.Text是否为Null值,则应使用String.IsNullOrEmpty().
private void button_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(textBox_Results.Text) Clipboard.SetText(textBox_Results.Text);
//rest of the code goes here;
}
Run Code Online (Sandbox Code Playgroud)
您应该像这样做我的支票:
if (textBox_Results != null && !string.IsNullOrWhiteSpace(textBox_Results.Text))
Run Code Online (Sandbox Code Playgroud)
只是一个额外的检查,所以如果textBox_Results是以往null你没有得到一个空引用异常.