我有下面的说明性代码。我需要条件1的输出右对齐并用零填充,如 |1234500000|而不是 |0000012345|而不是 and ,固定宽度为 10。格式字符串是有条件的,这意味着根据某些条件可以有多种可能的格式字符串之一,而只有一行用于输出。因此,像 PadRight 和 PadLeft 这样的函数不能与 value 一起使用,除非有办法在仍然具有相同的输出行的情况下使用它们。 (.NET 4.5)
我怎样才能得到|1234500000|同时满足这些要求?
string format;
if (condition1)
format = "|{0:0000000000}|";
else
if (condition2)
format = "|{0}|";
//more conditions here
Int64 value = 12345;
string a = String.Format(format, value);
a.Dump();
最佳答案
内置和可自定义的字符串格式只有这么多。也许您可以为每个条件设置不同的格式化函数,然后稍后调用它:
Func<Int64, String> formatter;
if (condition1)
{
formatter = (number) => number.ToString().PadRight(10, '0');
}
else if (condition2)
{
formatter = (number) => number.ToString();
}
Int64 sample = 12345;
string output = string.Format("|{0}|", formatter(sample));
output.Dump();
另一种选择是通过实现 IFormatProvider
和 ICustomFormatter
创建您自己的自定义字符串格式提供程序。例如,这是一个可以进行正确填充的草率的:
public class RightPaddedStringFormatter : IFormatProvider, ICustomFormatter
{
private int _width;
public RightPaddedStringFormatter(int width)
{
if (width < 0)
throw new ArgumentOutOfRangeException("width");
_width = width;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
// format doubles to 3 decimal places
return arg.ToString().PadRight(_width, '0');
}
public object GetFormat(Type formatType)
{
return (formatType == typeof(ICustomFormatter)) ? this : null;
}
}
然后您可以使用您的条件来选择格式化程序,例如:
IFormatProvider provider;
if (condition1)
{
provider = new RightPaddedStringFormatter(10);
}
...
Int64 sample = 12345;
string output = string.Format(provider, "|{0}|", sample);
output.Dump();
关于c# - 如何在使用动态格式时使用 string.format 向右填充零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28750388/