简体   繁体   English

C#中的NulltoString eq

[英]NulltoString eq in C#

I have this method to validate email addresses: 我有这种方法来验证电子邮件地址:

public static bool isEmail(string inputEmail)
{
    inputEmail = NulltoString(inputEmail);
    string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                      @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                      @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
    Regex re = new Regex(strRegex);
    if (re.IsMatch(inputEmail))
        return (true);
    else
        return (false);
}

But I get the error: The name 'NulltoString' does not exist in the current context . 但我得到错误: The name 'NulltoString' does not exist in the current context

Is there a string method that is equivalent to NulltoString() ? 是否有一个等效于NulltoString()string方法?

C#语言已经有了一个很好的功能, null-coalescing运算符

inputEmail = inputEmail ?? string.Empty;

尝试使用以下内容:

inputEmail = inputEmail ?? String.Empty;

I suggest 我建议

 public static bool isEmail(string inputEmail)
{
    inputEmail = inputEmail?? string.Empty;
    string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
          @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
          @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
    Regex re = new Regex(strRegex);
    if (re.IsMatch(inputEmail))
        return (true);
    else
        return (false);
}

More efficient than that: 效率更高:

     if (null == inputEmail)
         return false;

You could try 你可以试试

if(string.IsNullOrEmpty(inputEmail))
    //throw exception

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

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