我刚开始使用 C#,遇到了一些问题。 有什么方法可以像下面这样编写与 VB.NET Select 语句等效的 C# 代码吗?
Select Object.Name.ToString()
Case "Name1"
'Do something
Case "Name2"
'Do something else
Case Else
'Do the default action
End Select
如有任何帮助,我们将不胜感激。
感谢您到目前为止的意见,如果我将多个控件挂接到一个事件处理程序,如下所示,并且我想对每个控件执行稍微不同的操作,该怎么办:
Private Sub Button_Click(sender as Object, e as EventArgs) _
Handles button1.Click, Button2.Click
'do a general activity
Select CType(sender, Button).Name
Case button1.Name
'do something
Case button2.Name
'do something else
Case Else
'do the defalut action
End Select
End Sub
有没有办法在 C# 中执行上述 select 语句而不必使用嵌套 ifs?
最佳答案
随着时间的推移,我发现一些 VB.NET Select...Case
结构不适用于 C#,唯一的解决方法是编写大量 ifs。
例如,在 VB.NET 中,您可以这样写:
Dim num as Integer = 5
Select Case num
Case 1 to 10
'do something
Case 11 to 20
'do another thing
Case Else
'do the default
End Select
但 C# 中没有switch
结构允许您执行此类操作。你必须像这样在回旋处编码:
int num = 5;
switch (num)
{
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
//do something
break;
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 20:
//do something else
break;
default:
//do the default
break;
}
或者,如果您碰巧使用 Double
或任何由连续值而非离散值组成的类型,则必须使用 if
来获取所需的操作。
原因? C# 的 switch
需要各种 case
的常量。这与 VB.NET 的 Select Case
不同,后者允许写入范围。
关于c# - VB.NET Select...C# 中等效的 Case 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2447065/