Convert int to string?

我如何将一个int数据类型转换为C#中的string数据类型?


string myString = myInt.ToString();

string s = i.ToString();
string s = Convert.ToString(i);
string s = string.Format("{0}", i);
string s = $"{i}";
string s = "" + i;
string s = string.Empty + i;
string s = new StringBuilder().Append(i).ToString();

Just in case you want the binary representation and you're still drunk from last nights party:

private static string ByteToString(int value)
{
    StringBuilder builder = new StringBuilder(sizeof(byte) * 8);
    BitArray[] bitArrays = BitConverter.GetBytes(value).Reverse().Select(b => new BitArray(new []{b})).ToArray();
    foreach (bool bit in bitArrays.SelectMany(bitArray => bitArray.Cast<bool>().Reverse()))
    {
        builder.Append(bit ? '1' : '0');
    }
    return builder.ToString();
}

Note: Something about not handling endianness very nicely...

Edit: If you don't mind sacrificing a bit of memory for speed, you can use below to generate an array with pre-calculated string values:

static void OutputIntegerStringRepresentations()
{
    Console.WriteLine("private static string[] integerAsDecimal = new [] {");
    for (int i = int.MinValue; i < int.MaxValue; i++)
    {
        Console.WriteLine("t"{0}",", i);
    }
    Console.WriteLine("t"{0}"", int.MaxValue);
    Console.WriteLine("}");
}
链接地址: http://www.djcxy.com/p/51568.html

上一篇: C#如何使用另一个窗口的标志?

下一篇: 将int转换为字符串?