0

这是我的 vb.net 代码:

  Private Function PartOK(ByVal sPart As String) As Boolean
    Dim sCheck As String
    sCheck = "1234567890"
    PartOK = False
    sPart = Trim(sPart)

    If (Len(sPart) = PART_LENGTH) Or (IsNumeric(sPart)) Then
        Select Case sPart
            Case New String("1", PART_LENGTH), New String("2", PART_LENGTH), New String("3", PART_LENGTH)
            Case New String("4", PART_LENGTH), New String("5", PART_LENGTH), New String("6", PART_LENGTH)
            Case New String("7", PART_LENGTH), New String("8", PART_LENGTH), New String("9", PART_LENGTH)
            Case New String("0", PART_LENGTH), Left(sCheck, PART_LENGTH), Left(StrReverse(Left(sCheck, PART_LENGTH)), PART_LENGTH)
            Case Else : PartOK = True
        End Select
    End If
End Function

这个函数我转换成c#。但我不明白开关盒。

你们能解释一下吗?

4

2 回答 2

4

这是年度混淆代码奖的有力竞争者。C# switch语句没有 VB.NET Select 语句几乎相同的灵活性,因此无法直接转换。在这种情况下,一个又好又快的替代品是 HashSet。它应该类似于这样(假设 PART_LENGTH 为 5):

    private static HashSet<string> badParts = new HashSet<string> { 
        "00000", "11111", "22222", "33333", "44444", "55555", 
        "66666", "77777", "88888", "99999", "01234", "98765" 
    };

请注意,如果 PART_LENGTH 不是 10,则原始代码中的 Left() 案例可能是一个错误。您肯定想编写代码来填充它,但我这样保留它是为了更清楚地看到被拒绝的内容。那么测试字符串就变成了:

    public static bool PartOK(string part) {
        long partNumber;
        if (part.Length != badParts[0].Length) return false;
        if (!long.TryParse(part, out partNumber)) return false;
        if (badParts.Contains(part)) return false;
        return true;
    }
于 2012-05-19T09:37:08.177 回答
2

这个函数我转换成c#。但我不明白开关盒。

我假设您的意思是当您尝试将其转换为 C# 时,您收到了错误。查看转换后的代码和错误会很有用,但没关系......它也没有帮助您的 VB 代码甚至没有使用 Option Strict On 进行编译。

在 C# 中,case表达式必须是编译时常量 - 您不能直接指定范围或多个值(您指定多个情况)。基本上,C# switch/case 语句比 VB 中的限制性更强。

尚不完全清楚您的代码试图实现什么,但在 C# 中,您几乎可以肯定只需要使用 if/else 语句。甚至只是一个表达式:

// Names changed for sanity. You could use the VB IsNumeric function, or
// consider *exactly* what you want - int.TryParse, long.TryParse or
// decimal.TryParse may be appropriate. Also note that I've changed your "Or"
// into an "And" as that's the only thing that makes sense...
return part.Length == ValidPartLength && 
       IsNumeric(part)) &&
       part != new string(part[0], ValidPartLength) &&
       part != "1234567890".Substring(0, ValidPartLength) &&
       part != "0987654321".Substring(0, ValidPartLength);
于 2012-05-19T09:00:00.683 回答