我发现将一段代码从 C# 转换为 VB.NET 的情况很奇怪,该代码是一个小类,可以从基数 10 转换为基数 36,反之亦然。
关键是这个功能:
/// <summary>
/// A Base36 De- and Encoder
/// </summary>
public static class Base36
{
private const string CharList = "0123456789abcdefghijklmnopqrstuvwxyz";
/// <summary>
/// Encode the given number into a Base36 string
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static String Encode(long input)
{
if (input < 0) throw new ArgumentOutOfRangeException("input", input, "input cannot be negative");
char[] clistarr = CharList.ToCharArray();
var result = new Stack<char>();
while (input != 0)
{
result.Push(clistarr[input % 36]);
input /= 36;
}
return new string(result.ToArray());
}
在 VB.NET 中转换的结果应该是:
Public NotInheritable Class Base36
Private Sub New()
End Sub
Private Const CharList As String = "0123456789abcdefghijklmnopqrstuvwxyz"
''' <summary>
''' Encode the given number into a Base36 string
''' </summary>
''' <param name="input"></param>
''' <returns></returns>
Public Shared Function Encode(input As Int64) As String
If input < 0 Then
Throw New ArgumentOutOfRangeException("input", input, "input cannot be negative")
End If
Dim clistarr As Char() = CharList.ToCharArray()
Dim result = New Stack(Of Char)()
While input <> 0
result.Push(clistarr(input Mod 36))
input /= 36
End While
Return New String(result.ToArray())
End Function
问题是 VB.NET 中的模运算符与 C# 中的 % 余数运算符的执行方式不同,事实上,如果您在 C# 中调用 encode 方法:
long l = 13072113072399;
string result = Base36.Encode(l); //Result is : 4mt8um0b3
在 C# 中调用方法时:
Dim l As Int64 = 13072113072399
Dim result As String = Base36.Encode(l) //Result is : 5nujsu3ar
差异的原因是模运算符在某些情况下返回的结果不同,为什么?
VB.NET 中 % 余数运算符的等价物是什么?