我想要一個靈活的模板,可以翻譯類似的案例:
- WHnnn => WH001, WH002, WH003...(nnn 只是一個表示 3 位數字的數字)
- INVyyyyMMdd => INV20220228
- ORDERyyyyMMdd-nnn => ORDER20220228-007
我知道我可以使用以下代碼來實作特定的模板:
string.Format("INV{0:yyyy-MM-dd}", DateTime.Now)
這應該與上面的案例 2 具有相同的結果。但這并不靈活。因為客戶可以定制自己的模板,只要我能理解/支持,比如上面的第三種情況。
我知道即使是第三種情況,我也可以這樣做:
string.Format("ORDER{0:yyyy-MM-dd}-{1:d3}", DateTime.Now, 124)
但這很笨拙,因為我希望模板(輸入)就像這樣:
ORDERyyyyMMdd-nnn
要求是在 C# 中通過 string.Format 支持所有支持的模式,但模板可以是這些模式的任意組合。
uj5u.com熱心網友回復:
對于這種情況,我可能會使用自定義格式化程式。
創建一個包含日期/時間和數字并將實作IFormattable介面的新類。
有一個提示:在樣式中使用一些內部格式,INV{nnn}或者INV[nnn]只有其中的部分{}或[]將被替換為值。
否則可能會出現不需要的更改,例如Inv contains 'n'。你可以得到輸出為I7v.
在您的示例中N是大寫的,但即使在每次定制之后也是如此?
代碼(簡化版):
internal sealed class InvoiceNumberInfo : IFormattable
{
private static readonly Regex formatMatcher = new Regex(@"^(?<before>.*?)\[(?<code>\w ?)\](?<after>.*)$");
private readonly DateTime date;
private readonly int number;
public InvoiceNumberInfo(DateTime date, int number)
{
this.date = date;
this.number = number;
}
public string ToString(string format, IFormatProvider formatProvider)
{
var output = format;
while (true)
{
var match = formatMatcher.Match(output);
if (!match.Success)
{
return output;
}
output = match.Groups["before"].Value FormatValue(match.Groups["code"].Value) match.Groups["after"].Value;
}
}
private string FormatValue(string code)
{
if (code[0] == 'n')
{
var numberFormat = "D" code.Length.ToString(CultureInfo.InvariantCulture);
return this.number.ToString(numberFormat);
}
else
{
return this.date.ToString(code);
}
}
}
采用:
internal static class Program
{
public static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("No format to display");
return;
}
var inv = new InvoiceNumberInfo(DateTime.Now, number: 7);
foreach (string format in args)
{
Console.WriteLine("Format: '{0}' is formatted as {1:" format "}", format, inv);
}
}
}
并輸出:
Format: 'WH[nnn]' is formatted as WH007
Format: 'INV[yyyyMMdd]' is formatted as INV20220227
Format: 'ORDER[yyyyMMdd]-[nnn]' is formatted as ORDER20220227-007
注意這只是一個簡化版本,概念證明。對您的代碼使用適當的錯誤檢查。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/436149.html
上一篇:在框架內列印字串
