c# - string.empty 和 string.isnullorempty

标签 c# visual-studio winforms

我有一个这样的函数,它检查字段是否为空或什么,如果为空,则将 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 的扩展方法,但据我所知框架中没有。

关于c# - string.empty 和 string.isnullorempty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4312946/

相关文章:

C# 转换枚举 InvalidCastException 错误

c# - 管理表单状态的最佳方法是什么?

winforms - ObservableCollection(Of T) vs BindingList(Of T)?

c# - .NET Web API 返回带有很多小数位的 double

c# - C# 中的 Foreach struct 奇怪的编译错误

c# - 强制 DateTime 变量仅显示日期而不转换 ToString()

c++ - 如何使用 msvs 包含和设置 brian gladman aes?

visual-studio - 如何在 Visual Studio 2010 中执行 "shell"图标嵌入?

.net - 在Visual Studio中缺少状态栏?

c# - 动态初始化窗体对象