将VB转换为C#-类型转换
作者:互联网
我需要帮助将某些代码从VB转换为C#.
Public Function ToBase36(ByVal IBase36 As Double) As String
Dim Base36() As String = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}
Dim v As String
Dim i As Decimal
Do Until IBase36 < 1
i = IBase36 Mod 36
v = Base36(i) & v
IBase36 = Math.DivRem(Long.Parse(IBase36), 36, Nothing)
Loop
Return v
End Function
我的问题是VB中类型转换的工作方式,这行给我带来了最大的麻烦,因为IBase36是双精度型,在这种情况下Math.DivRem()应该返回long,而Long.Parse()需要字符串.
IBase36 = Math.DivRem(Long.Parse(IBase36), 36, Nothing)
这是我翻译的工作代码,这要感谢JaredPar和其他人
public static string ToBase36(double IBase36)
{
string[] Base36 = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
string v = null;
long i = default(long);
while (!(IBase36 < 1))
{
IBase36 = Convert.ToDouble(Math.DivRem(Convert.ToInt64(IBase36), 36, out i));
v = Base36[i] + v;
}
return v;
}
解决方法:
要进行翻译,重要的是首先了解VB.Net代码的功能.在引擎盖下,它将基本上产生以下内容
Dim unused As Long
IBase36 = CDbl(Math.DivRem(Long.Parse(CStr(IBase36)), 36, unused)
注意:未使用的变量是必需的,因为第三个参数是out.转换为C#时,这是一个重要的区别.
上面最自然的C#等效项是
long unused;
IBase36 = Convert.ToDouble(Math.DivRem(Long.Parse(IBase36.ToString()), 36, out unused);
标签:implicit-conversion,vb-net,c 来源: https://codeday.me/bug/20191208/2091419.html