一开始没有像预期的那样工作

本文关键字:工作 一开始 | 更新日期: 2023-09-27 18:04:51

我有一个url,我需要检查它不以http://或https://开始,url的长度不超过493个字符。

到目前为止,我有这个条件语句:
else if (!url.Text.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
         !url.Text.StartsWith("https://", StringComparison.OrdinalIgnoreCase) &&
         url.Text.Length > 493)
    IsValid = false;

但是,当url确实有http://或https://

时,此返回true

不确定为什么会这样?

一开始没有像预期的那样工作

您需要&&而不是||,假设您的字符串以https开始,那么首先检查StartsWith("http://"将给出true。如果文本以http

开头,同样适用
else if (!url.Text.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !url.Text.StartsWith("https://", StringComparison.OrdinalIgnoreCase) && url.Text.Length > 493)
                IsValid = false;

你可以用||组合这两个条件,用!

if (!(url.Text.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || url.Text.StartsWith("https://", StringComparison.OrdinalIgnoreCase)  && url.Text.Length > 493)

您需要将|| in更改为&&

url将以httphttps开头,这意味着它们中的一个将始终为真。你需要用&&

检查它们

导致问题的是||&&逻辑

将其重写为嵌套的if以使其更清晰

private static bool IsValidUrl(string url)
{
    if(url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || 
       url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
       if(url.Text.Length < 493)
           return true;
    return false;
}