【问题标题】:Switch case in VBVB中的切换案例
【发布时间】:2012-05-19 08:31:26
【问题描述】:

这是我的 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#。但我不懂开关盒。

你们能解释一下吗?

【问题讨论】:

  • 这...作为 VB.NET 代码真的没有任何意义。它有什么作用,为什么要这样写?
  • 我真的不明白你的问题是什么?你想知道开关盒的作用吗?或者您想知道如何将其转换为 C#?
  • 我想知道那个开关盒是如何工作的。
  • 你怎么知道它有效工作?谁写的代码?你是从哪里弄来的? 应该做什么?

标签: c# vb.net vb.net-to-c#


【解决方案1】:

这是年度混淆代码奖的有力竞争者。 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;
    }

【讨论】:

  • +1。如果 PART_LENGTH 可以在运行时变化,那么当然可以动态构建 badParts。与 long.TryParse 不同,VB IsNumeric 也允许带小数点和指数的字符串。这可能是原始 VB 中的一个错误!
【解决方案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);

【讨论】:

  • 你的c#表达式很简洁但与VB不匹配?那么字符的升序和降序序列(sCheck)“1234...N”和“N...321”,其中 N 是 PART_LENGTH
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-30
  • 2014-02-01
相关资源
最近更新 更多