VB.NET Select Case - 正确的说法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14503373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:00:59  来源:igfitidea点击:

VB.NET Select Case - what is the correct statement?

vb.netselect-case

提问by Brandon

Why doesn't the following code work?

为什么下面的代码不起作用?

Private Function resolveSiteName(ByVal plantName As String, ByVal siteName As String) As Integer
    Dim siteId As Integer = Nothing
    Dim fullName As String = plantName & siteName
    Select Case fullName
        Case fullName.Contains("Example" And "Example2" And "Example3")
            siteId = 0
    End Select
    Return siteId
End Function

I'm guessing my Select Case fullNameis wrong, because when debugging it, the conditions are met and it just skips over assigning the siteId.

我猜我Select Case fullName是错的,因为在调试它时,条件得到满足,它只是跳过分配siteId.

I also tried just this

我也试过这个

Case fullName.Equals("Exactly what full name is")

just to test to see if that would work...and it still skipped over the assigning part.

只是为了测试看看这是否有效......它仍然跳过了分配部分。

What am I missing here?

我在这里错过了什么?

回答by Ric

This should work too:

这也应该有效:

Select Case fullName
   Case "Example", "Example2", "Example3"
      siteId = 0
End Select

回答by Tim Schmelter

Note that this would not even compile if you'd use an If-clause(which is more appropriate here):

请注意,如果您使用If-clause(这里更合适),这甚至不会编译:

If fullName.Contains("Example" And "Example2" And "Example3") Then
    ' this doesn't compile since you cannot concat a string with And
    ' you want to check if fullName equals to one of the strings anyway
    siteId = 0
End If

If you want to check multiple items at once, define a collection, add all to it and then use Contains:

如果要一次检查多个项目,请定义一个集合,将所有项添加到其中,然后使用Contains

Dim siteNames = { "Example", "Example2", "Example3" }
If siteNames.Contains(fullName) Then
    siteId = 0
End If

回答by Steven Ackley

Try this:

尝试这个:

Select Case fullName
   Case "Example"
      siteId = 0
   Case "Example2"
      siteId = 0
   Case "Example3"
      siteId = 0
End Select

回答by SysDragon

This solves your problem:

这可以解决您的问题:

Select Case True
    Case fullName.Contains("Example")
        siteId = 0
End Select

Or for your second try:

或者您的第二次尝试:

Select Case fullName
    Case "Exactly what full name is"
        siteId = 0
End Select    

回答by Isaac Ali

Replace

代替

Select Case fullName

with

Select Case True