包含Unicode字符检查失败

时间:2013-05-30 15:14:36

标签: c# .net .net-4.0

    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。

我收到错误消息: “ContainsUnicodeCharacter(char [])':并非所有代码路径都返回值”

这里出了什么问题,请帮忙。 谢谢。

4 个答案:

答案 0 :(得分:5)

您的方法没有经过深思熟虑。它可以做得更简单:

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

你有两个嵌套的循环没有理由。

我使该方法成为一种普遍适用的扩展方法。

答案 1 :(得分:3)

您需要在最后return true;之前添加},但我也认为您的测试已经逆转:

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;
}

答案 2 :(得分:3)

继续@ egrunin的回答,我不知道你为什么循环遍历所有字符,然后将它们转换为字符串,这样你就可以在生成的字符数组上使用Linq方法。您可以像这样简化整个方法(保持相同的逻辑):

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

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

答案 3 :(得分:0)

你只有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;  
    }