C#增量数字字符串
我有一个静态字符串: 静态字符串SERIAL=“000” 在一定条件下,我需要增加1。例如,该值应如下所示:C#增量数字字符串,c#,string,auto-increment,C#,String,Auto Increment,我有一个静态字符串: 静态字符串SERIAL=“000” 在一定条件下,我需要增加1。例如,该值应如下所示: 001 002 003 等等 我尝试了不同的方法,但没有找到答案。您可以将序列值设置为整数,然后定义一个getter,它将以所需格式的字符串形式返回值。通过这种方式,您可以简单地增加序列号的数值 例如: public class Program { static void Main(string[] args) { Console.WriteLine(C
001
002
003
等等
我尝试了不同的方法,但没有找到答案。您可以将序列值设置为整数,然后定义一个getter,它将以所需格式的字符串形式返回值。通过这种方式,您可以简单地增加序列号的数值 例如:
public class Program
{
static void Main(string[] args)
{
Console.WriteLine(Counter.SerialString);
Counter.Serial++;
Console.WriteLine(Counter.SerialString);
Console.ReadKey();
}
public class Counter
{
public static int Serial;
public static string SerialString
{
get
{
return Serial.ToString("000");
}
}
}
}
您可以将序列值设置为整数,并定义一个getter,该getter将以所需格式的字符串形式返回值。通过这种方式,您可以简单地增加序列号的数值 例如:
public class Program
{
static void Main(string[] args)
{
Console.WriteLine(Counter.SerialString);
Counter.Serial++;
Console.WriteLine(Counter.SerialString);
Console.ReadKey();
}
public class Counter
{
public static int Serial;
public static string SerialString
{
get
{
return Serial.ToString("000");
}
}
}
}
如果序列长度始终为3位,则可以使用整数,当需要它作为字符串时,只需调用其
ToString()
方法。如果序列长度始终为3位,则可以使用整数,当需要它作为字符串时,只需调用其ToString()
方法。一种方法是在ToString方法上使用PadLeft方法
int n = 000;
for (int i = 0; i < 100; i++)
{
n++;
Console.WriteLine(n.ToString().PadLeft(3, '0'));
}
Console.ReadLine();
int n=000;
对于(int i=0;i<100;i++)
{
n++;
Console.WriteLine(n.ToString().PadLeft(3,'0');
}
Console.ReadLine();
这里是方法头
公共字符串PadLeft(int totalWidth,char paddingChar) 一种方法是在ToString方法上使用PadLeft方法
int n = 000;
for (int i = 0; i < 100; i++)
{
n++;
Console.WriteLine(n.ToString().PadLeft(3, '0'));
}
Console.ReadLine();
int n=000;
对于(int i=0;i<100;i++)
{
n++;
Console.WriteLine(n.ToString().PadLeft(3,'0');
}
Console.ReadLine();
这里是方法头
公共字符串PadLeft(int totalWidth,char paddingChar) 为什么要使用字符串?事实上,使用
int
,递增它,然后只需调用mySerialInt.ToString(“000”)
向我们展示您的代码并询问您自己的一些发现……正如Chris Sinclair所说,您应该使变量类型最接近将对其执行的操作;在您的例子中,当值是int而不是字符串时,执行增量要简单得多,也更容易理解。相反,如果将值连接在一起,那么使用字符串比使用int更有意义。将值保持在最有机的形式,然后在必要时应用格式以特定的抽象形式呈现它们。感谢大家的快速响应@Chris Sinclair你的回答解决了我的问题,很简单。非常感谢。您为什么要使用字符串?事实上,使用int
,递增它,然后只需调用mySerialInt.ToString(“000”)
向我们展示您的代码并询问您自己的一些发现……正如Chris Sinclair所说,您应该使变量类型最接近将对其执行的操作;在您的例子中,当值是int而不是字符串时,执行增量要简单得多,也更容易理解。相反,如果将值连接在一起,那么使用字符串比使用int更有意义。将值保持在最有机的形式,然后在必要时应用格式以特定的抽象形式呈现它们。感谢大家的快速响应@Chris Sinclair你的回答解决了我的问题,很简单。非常感谢你。