简体   繁体   中英

Length of a method in VB.NET

How does VB.NET calculate the length of a method? How can I do this in C#?

This my VB.NET code:

Private Function ZeroPad(ByRef pNumber As Integer, ByRef pLength As Integer) As String
    Dim Padding As Object
    If IsNumeric(pNumber) And IsNumeric(pLength) Then
        Padding = New String("0", pLength)
        ZeroPad = Padding & CStr(pNumber)
        ZeroPad = Right(ZeroPad, pLength)
    Else
        ZeroPad = CStr(pNumber)
    End If
End Function

I converted into C# as follows:

private string ZeroPad(ref int pNumber, ref int pLength) {
    object Padding;
    if ((IsNumeric(pNumber) && IsNumeric(pLength))) {
        Padding = new string("0", pLength);
        return (Padding + pNumber.ToString());

        ZeroPad = ZeroPad.Substring((ZeroPad.Length - pLength));

        // In the above line, how can I take the length of a method in C#?
    }
    else {
        return pNumber.ToString();
    }
}

You are probably confused between the variable ZeroPad and the method ZeroPad . It is customary to write variable names with a lower case initial character, eg zeroPad . To return a value from a method, use return in C#. I'm not sure what the purpose is of your IsNumeric subroutine or why you take value by reference, but your code in C# would be similar to:

private string ZeroPad(ref int pNumber, ref int pLength)
{
    string padding;
    string zeroPad;
    if ((IsNumeric(pNumber) && IsNumeric(pLength)))
    {
        padding = new string('0', pLength);
        zeroPad = (padding + pNumber.ToString());

        zeroPad = zeroPad.Substring((zeroPad.Length - pLength));
    }
    else
    {
        zeroPad = pNumber.ToString();
    }
    return zeroPad;
}

As you don't change the values of pNumber or pLength , you can pass them by value ( ByVal in Visual Basic). And knowing that both pNumber and pLength are integers, and therefore always numeric, your method could be shortened to the following:

private string ZeroPad(int pNumber, int pLength)
{
    string zeroPad;
    string padding = new string('0', pLength);

    zeroPad = (padding + pNumber.ToString());

    zeroPad = zeroPad.Substring(zeroPad.Length - pLength);

    return zeroPad;
}

The .NET Framework's Base Class Libraries have a String.PadRight method that does exactly what you want if you specify '0' as the value for paddingChar .

In C#, you don't assign to method name. Instead you use a "return" statement. Declare a variable:

string retVal;

And instead of

ZeroPad = some_value;

use:

retVal = some_value;

and at last return retVal:

return retVal;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM