TextBox 的 text 属性甚至可能为空吗? [英] Is it even possible for the text property of a TextBox to be null?

查看:61
本文介绍了TextBox 的 text 属性甚至可能为空吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这个代码:

if (txtUPC.Text.ToString() != null)

...并想知道这个测试是否有效 - text 属性是否可能为空?txtUPC 不是动态创建的控件.当然,它可以是空的,也可以只包含空格,但为空?如果是这样,我想知道如何.再说一次,在 text 属性上调用 ToString() 看起来也像穿着带腰带的吊带一样.

...and wonder if this test is even valid - is it possible for the text property to be null? txtUPC is not a dynamically created control. It can be empty, of course, or contain just whitespace, but null? If so, I'd like to know how. Then again, call ToString() on the text property seems like wearing suspenders with a belt, too.

所以在我看来,对我来说(记住:.NET 1.1,Windows CE/Compact Framework),这个:

So it seems to me, that for me (remember: .NET 1.1, Windows CE/Compact Framework), this:

if (txtUPC.Text.Trim() != string.Empty)

...比这更好的测试:

...is a better test than this:

if (txtUPC.Text.ToString() != null) 

然而,在更专注地注视这段代码时,无论如何,似乎无论是外部还是内部手套都是多余的/不必要的.请注意该方法包含的两个 shibbeleth-pronunciation-checkers:

However, upon gazing even more intently at this code, it seems that either the outer or the inner gauntlet is redundant/unnecessary, anyway. Note the two shibbeleth-pronunciation-checkers that the method includes:

if (txtUPC.Text.ToString() != null) 
{
    if (txtUPC.Text.Length > 0)
    {
                    . . .
    else
    {
        MessageBox.Show("Please enter a value in the item field");
        txtUPC.Focus();
    }
}
else
{
    MessageBox.Show("Please enter a value in the item field");
    txtUPC.Focus();
}
. . .

似乎一个看门人/护手就足够了 - 要么这样检查:

It would seem one gatekeeper/gauntleteer would be enough - either checking this way:

if (txtUPC.Text.Trim() != string.Empty)

...或者这样:

if (txtUPC.Text.Trim().Length > 0)

一个?

推荐答案

我看到该代码的问题是 .ToString() 将对象作为字符串返回.如果在这种情况下,对象是一个字符串,它只返回原始字符串(原样)

The problem I see with that code is that .ToString() returns the object as a String. If in this case, the object is a String it just returns the original string (exactly as is)

问题是如果.Text 为null,那么.ToString() 的方法调用会抛出一个NullReferenceException.

Problem is if .Text is null, then the method call of .ToString() would throw a NullReferenceException.

您可以在 .ToString 覆盖上看到更多内容这里

You can see more on the .ToString override here

请参阅此代码以获取示例:

See this code for an example:

String str1 = "";
String str2 = null;

Console.WriteLine("Original str1: {0}", str1);
Console.WriteLine("Original str2: {0}", str2);

Console.WriteLine("ToString str1: {0}", str1.ToString());
Console.WriteLine("ToString str2: {0}", str2.ToString());

将在 ToString str2 行上抛出异常

这篇关于TextBox 的 text 属性甚至可能为空吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆