C# stackalloc 函数
2019-12-24 本文已影响0人
李药师_hablee
贴代码
using System;
namespace ConsoleApp3
{
class Program
{
unsafe static string IntToString(int value)
{
char* buffer = stackalloc char[16];
char* p = buffer + 16;
int n = value >= 0 ? value : -value;
do
{
*--p = (char)(n % 10 + '0');
n /= 10;
} while (n != 0);
if (value < 0)
*--p = '-';
return new string(p, 0, (int)(buffer + 16 - p));
}
static void Main(string[] args)
{
Console.WriteLine(IntToString(12345));
Console.WriteLine(IntToString(-999));
//Console.WriteLine("Hello World!");
}
}
}
遇到编译问题,请参考这篇文章