这是我的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#。但我不明白转换案例。
你能解释一下吗?
答案 0 :(得分:4)
这是年度奖项混淆代码的有力竞争者。 C#开关语句与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;
}
答案 1 :(得分: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);