C#:关于System.ArgumentNullException
私有无效Go2_单击(对象发送方,事件参数e) { 尝试 {C#:关于System.ArgumentNullException,c#,.net,C#,.net,私有无效Go2_单击(对象发送方,事件参数e) { 尝试 { static void X(String a,String b,String c) { TextBox textBox3 = new TextBox(); a = textBox3.Text; if (a == " ") { throw new ArgumentNullException(a);
static void X(String a,String b,String c)
{
TextBox textBox3 = new TextBox();
a = textBox3.Text;
if (a == " ")
{
throw new ArgumentNullException(a);
}
TextBox textBox4 = new TextBox();
b = textBox4.Text;
if (b == null)
{
throw new ArgumentNullException(b);
}
TextBox textBox5 = new TextBox();
c = textBox5.Text;
if (c == null)
{
throw new ArgumentNullException(c);
}
}
}
我的程序无法执行System.ArgumentNullException。如何解决此程序?请参阅指南。尝试,而不是:
........//my code
X(Sx,Sy,V);
........// my some code
}
catch (System.ArgumentNullException)
{
MessageBox.Show("Your String is not correct");
}
这:
throw new ArgumentNullException(c);
catch (System.ArgumentNullException)
{
MessageBox.Show("Your String is not correct");
}
您需要使用
string.IsNullOrEmpty()
检查字符串
变量的值。当您在方法中使用textbox.Text
为它们赋值时,它们会得到字符串。为它们赋值的值为空。if语句永远不会演变为true
,也不会引发异常。
如果你像这样改变你的条件那就行了
throw new ArgumentNullException("Your String is not correct");
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
要检查字符串是否为null,请为此使用专用函数,并使用参数名而不是参数初始化ArgumentNullException
例如,而不是
if (string.IsNullOrWhiteSpace(a))
{
throw new ArgumentNullException("Thrown from first condition");
}
写
为了
写
if (c == null)
{
throw new ArgumentNullException(c);
}
请正确格式化您的代码。string.empty不同于a==“”。请改为检查string.IsNullOrWhiteSpace。您需要使用string.IsNullOrEmpty()
要检查值,当您从方法X内的不同文本框中获取参数时,为什么要将参数传递给方法X?这对我来说没有任何意义?请使用IF块内的string.IsNullOrEmpty()进行比较,而不是将其与“”进行比较或Null您实际上没有检查方法参数,因此不应抛出ArgumentNullException。最好创建您自己的特定InvalidInputValueException或类似的描述性消息。捕获常规异常是一种不好的做法。因此,您可以将“Exception ex”更改为“ArgumentNullException ex”IMHO、IsNullOrWhiteSpace和IsNullOrEmpty应该导致ArgumentException,而不是ArgurmentNullException。您对IsNullOrWhiteSpace的权利,但对于IsNullOrEmpty,这是上下文的问题;)通常我会为if(c==null)抛出ArgumentNullException,但这是ArgumentNullException的问题。
if (string.IsNullOrWhiteSpace(a))
{
throw new ArgumentNullException("a");
}
if (c == null)
{
throw new ArgumentNullException(c);
}
if (string.IsNullOrEmpty(c))
{
throw new ArgumentNullException("c");
}