簡體   English   中英

包含Unicode字符檢查失敗

[英]Contains Unicode Character checking fail

    public bool ContainsUnicodeCharacter(char[] input)
    {
        const int MaxAnsiCode = 255;
        bool temp;
        string s;

        foreach (char a in input)
        {
            s = a.ToString();
            temp = s.Any(c => c > MaxAnsiCode);

            if (temp == false)
            {
                return false;
            }
        }            
    }

此代碼用於檢查unicode是否在輸入char數組上存在。

我收到錯誤消息:“ ContainsUnicodeCharacter(char [])':並非所有代碼路徑都返回值”

這里出了什么問題,請幫忙。 謝謝。

您的方法沒有經過深思熟慮。 可以簡單得多:

public static bool ContainsUnicodeCharacter(this IEnumerable<char> input)
{
    const int MaxAnsiCode = 255;
    return input.Any(c => c > MaxAnsiCode);
}

您沒有理由在那里有兩個嵌套循環。

我將該方法作為普遍適用的擴展方法。

您需要添加return true; 就在last }之前,但我也認為您的測試已經顛倒了:

public bool ContainsUnicodeCharacter(char[] input)
{
    const int MaxAnsiCode = 255;
    bool temp;
    string s;

    foreach (char a in input)
    {
        s = a.ToString();
        temp = s.Any(c => c > MaxAnsiCode); // true if unicode found

        if (temp == true)
        {
            return true;
        }
    }

    return false;
}

除了@egrunin的答案,我不知道為什么循環瀏覽所有字符,然后將它們強制轉換為字符串,只是為了可以在結果字符arrayt上使用Linq方法。 您可以像這樣簡化整個方法(保持相同的邏輯):

public bool ContainsUnicodeCharacter(char[] input)
{
    const int MaxAnsiCode = 255;

    return input.Any(c => c > MaxAnsiCode);
}

您只有1個return語句,如果有條件的話,這是條件語句的一部分return true; 但是出現該錯誤的原因是,如果temp永遠不等於false,則函數將不返回任何內容

public bool ContainsUnicodeCharacter(char[] input)
    {
        const int MaxAnsiCode = 255;
        bool temp;
        string s;

        foreach (char a in input)
        {
            s = a.ToString();
            temp = s.Any(c => c > MaxAnsiCode);
            if (temp == false)
            {
               return false;
             }
        } 
         return true;  
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM