繁体   English   中英

string.empty和string.isnullorempty

[英]string.empty and string.isnullorempty

我有一个类似这样的函数,它检查该字段是否为空或什么,如果为空,则将setError图标放在文本框旁边。

      private bool ValidateHost()
      {
        ErrorProvider errorProvider = new ErrorProvider();
        bool isValid = true;

        //If the txtHost is empty, show a message to user            
        if(txtHost.Text == string.Empty)
            {
            errorProvider.SetError(txtHost, "Please enter the host address");
            isValid = false;
            }
        else
            errorProvider.SetError(txtHost, string.Empty);
        return isValid;
      }

但是当我尝试使用string,isnullorempty时,我没有得到seterror图标。你们能告诉我在这种情况下使用string.isnullorempty的正确方法是什么。

我的猜测是您试图像使用实例方法一样使用它,如下所示:

if (txtHost.Text.IsNullOrEmpty())

它不是实例方法,而是静态方法,因此您可以这样使用它:

if (string.IsNullOrEmpty(txtHost.Text))

它不是实例方法,因为如果txtHost.Text为null,则该方法调用将抛出NullReferenceException ,而这正是我们要避免的情况。

可以编写一种扩展方法来应对null,但据我所知,框架中没有一个扩展方法。

string.IsNullorEmpty()是一个静态方法,其调用方式如下:

if (string.IsNullOrEmpty(txtHost.Text))
{
    errorProvider.SetError(txtHost, "Please enter the host address"); 
    isValid = false;
}

如果空格,制表符等也无效,则也可以考虑使用类似的string.IsNullOrWhitespace

将您的IF条件更改为-

if( string.IsNullOrEmpty(txtHost.Text) ) 
{
  ...
}

难道这不是他字符串测试所必需的吗?

ErrorProvider errorProvider =新的ErrorProvider();

说真的 ErrorProvider应该存在于表单上。 您只是在动态创建一个(在hthe方法结束时变为无效),甚至没有将它们正确地挂接到表单中。

ErrorProvider应该放在表单上。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM