开发者

Translating VB to C# - type conversion

I need help with translating some code from VB to 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

My problem is how type conversion works in VB, and this line gives me most trouble since IBase36 is a double, Math.DivRem() in this case should return long and Long.Parse() need string.

IBase36 = Math.DivRem(Long.Parse(IBase36), 36, Nothing)开发者_如何转开发

Here is my translated, working code thanks to the JaredPar and others

    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;
    }


To translate it's important to understand first how the VB.Net code functions. Under the hood it will essentially generate the following

Dim unused As Long
IBase36 = CDbl(Math.DivRem(Long.Parse(CStr(IBase36)), 36, unused)

Note: The unused variable is necessary because the third argument is an out. This is an important difference when translating to C#.

The most natural C# equivalent of the above is

long unused;
IBase36 = Convert.ToDouble(Math.DivRem(Long.Parse(IBase36.ToString()), 36, out unused);


Now try it:

long unused = null;
IBase36 = Convert.ToDouble(Math.DivRem(Convert.ToInt64(IBase36), 36, out unused));


IBase36  = (long)IBase36 / 36;

is what you want. Math.DivRem() returns the quotient which the above integer division should take care of. The third out parameter returns the remainder but since you don't care about it in vb. net code, you can just ignore that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜