【问题标题】:Select Case True in VB.NET在 VB.NET 中选择 Case True
【发布时间】:2012-12-20 09:56:21
【问题描述】:

我有以下选择案例,我想对字符串包含的内容进行一些检查,并为每个案例调用一些函数。但似乎如果多个条件为真,它只考虑第一个条件。问题是我有大约 113 个不同的案例。

我必须为每种情况使用一个 if 语句吗?

   Select Case True
          Case command.ToUpper.Contains(" S:")
'Do something
          Case command.ToUpper.Contains(" C:")
'Do something
          Case command.ToUpper.Contains(" *S")
'Do something
          Case command.ToUpper.Contains(" *C")
'Do something
          Case command.ToUpper.Contains(" CC")
'Do something
          Case command.ToUpper.Contains(" SS")
    End Select

【问题讨论】:

  • @Oded 完全不同的东西,最终它们将用于生成一个动态 sql 命令,该命令返回一个用于绘制数据的表
  • Select Case True 的可能重复项

标签: .net vb.net select-case


【解决方案1】:

这就是选择案例的定义方式。使用一系列 If 语句会起作用。

考虑一个表驱动的解决方案(伪代码):

For Each pat In patterns
  If command contains pattern.pat
    perform pattern.action

【讨论】:

    【解决方案2】:

    只是一个想法,但是呢

    dim tempCommand as string = command.ToUpper()
    dim match as boolean = true
    
    while match andalso tempCommand.length > 0
        select case true
            Case tempCommand.Contains(" S:")
                'Do something
                'then do this    
                tempCommand = tempCommand.replace(" S:","")
            Case tempCommand.Contains(" C:")
                'Do something
                'then do this
                tempCommand = tempCommand.replace(" C:","")
            Case tempCommand.Contains(" *S")
                'Do something
                'then do this
                tempCommand = tempCommand.replace(" *S","")
            Case tempCommand.Contains(" *C")
                'Do something    
                'then do this
                tempCommand = tempCommand.replace(" *C","")
            Case tempCommand.Contains(" CC")
                'Do something
                'then do this
                tempCommand = tempCommand.replace(" CC","")
            Case command.ToUpper.Contains(" SS")
                'then do this
                tempCommand = tempCommand.replace(" SS","")    
            case else match = false
        end select
    end while
    

    我假设基于各种标准您正在执行不同的操作,所以我不确定您将如何执行“执行 pattern.action”,除非这是一种我不知道的动态代码方式知道并且如果可以做到的话会非常酷。

    我的建议确实破坏了命令,这就是为什么我使用临时保存变量以便原始命令不会丢失,以防您在代码中进一步需要它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      • 2021-01-26
      • 1970-01-01
      • 2013-06-10
      相关资源
      最近更新 更多