我有一个这样的函数,它检查字段是否为空或什么,如果为空,则将 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/