如何正确将C#的Round方法转换为VB.NET?遇表达式错误
C#转VB.NET:解决is not/and not与switch表达式的转换错误
原C#代码
public decimal Round(decimal value) { if (value < 300) return value; if (((long)value % 10) is not 5 and not 9) return value; return (long)value + (((long)value / 10) % 10) switch { 0 => -10, 1 => -20, 2 or 7 => 20, 3 or 8 => 10, 5 => 40, 6 => 30, _ => 0, }; }
错误的VB.NET代码(出现"Expression Expected"错误)
Public Function Round(ByVal value As Decimal) As Decimal If value < 300 Then Return value End If If (TypeOf (CType(value Mod 10, Long)) Is Not 5 And Is Not CType(9, Integer)) Then Return value End If Return CType(value, Long) + ((CType(value / 10, Long)) Mod 10) switch { 0 => -10, 1 => -20, 2 Or 7 => 20, 3 Or 8 => 10, 5 => 40, 6 => 30, _ => 0, } End Function
问题分析与修正
你的VB.NET代码存在两处核心语法错误:
is not/and not转换错误:C#的is not用于值判断时,VB.NET不能用TypeOf ... Is Not(该语法仅用于类型或引用对象的比较),值类型需直接用不等于运算符<>或Not ... =,同时建议用AndAlso做短路逻辑与提升效率。- Switch表达式语法错误:VB.NET没有
switch关键字,对应功能需用Select Case表达式(要求VB 16.0及以上版本支持),语法结构与C#完全不同。
正确的VB.NET代码
Public Function Round(ByVal value As Decimal) As Decimal If value < 300 Then Return value End If Dim lastDigit As Long = CType(value Mod 10, Long) If lastDigit <> 5 AndAlso lastDigit <> 9 Then Return value End If Dim tensDigit As Long = CType(value / 10, Long) Mod 10 Dim adjustment As Long = Select Case tensDigit Case 0 : -10 Case 1 : -20 Case 2, 7 : 20 Case 3, 8 : 10 Case 5 : 40 Case 6 : 30 Case Else : 0 End Select Return CType(value, Long) + adjustment End Function
关键修正说明
- 条件判断优化:提取
lastDigit变量简化重复计算,用<> 5 AndAlso <>9替代错误的类型判断语法,AndAlso会在第一个条件为假时直接停止后续判断,比And更高效。 - Switch逻辑替换:用VB.NET原生的
Select Case表达式实现分支逻辑,多个匹配值用逗号分隔(Case 2,7对应C#的2 or7),Case Else对应C#的_默认分支。 - 可读性提升:提取
tensDigit变量拆分复杂计算,让代码结构更清晰,便于维护。
内容的提问来源于stack exchange,提问作者Arie
相关产品推荐
相关产品推荐

