values C, E, F, G, X
are among the standard format strings .我想添加另一个标准字符串...也许是字母“M”来扩展我的货币格式选项。我制作了一个 MoneyFormatInfo
类,它实现了必要的 IFormatProvider
和 ICustomFormatter
接口(interface)。它适用于我可以编造的所有场景,除了这个......
decimal cash = 3124.728m;
//Code '392' is JAPANESE YEN, with basic French formatting.
var frenchmen = new MoneyFormatInfo("392", new CultureInfo("fr-FR"));
result = cash.ToString("m", frenchmen);
Assert.AreEqual(result, "3 124,73 JPY");
我收到的错误消息是“FormatException 未被用户代码处理”。
我反射(reflect)了 BCL ToString
方法。我看到它只引用标准格式字符串列表;我没有看到任何可以让我解决这个问题的 Hook 点。我错过了什么吗?
以下是当前按预期工作的其他示例...
//Code '978' is the Euro
//The custom "Money" class holds an amount and currency type which
//intentionally cannot be overridden.
Money dough = new Money(8124.348m, "978");
decimal cash = 3124.728m;
string result;
//EURO currency parameters, with basic French formatting
var french = new CultureInfo("fr-FR");
result = String.Format(french, "the money: {0:m}", dough);
Assert.AreEqual(result, "the money: 8 124,35 EUR");
//JAPANESE YEN, with basic French formatting.
var frenchmen = new MoneyFormatInfo("392", new CultureInfo("fr-FR"));
result = String.Format(frenchmen, "the cash: {0:m}", cash);
Assert.AreEqual(result, "the cash: 3 124,73 JPY");
result = dough.ToString("c", frenchmen);
Assert.AreEqual(result, "8 124,35 €");
我的自定义 Money
类有一个 ToString() 覆盖,它执行状态更改,并将“M”格式字符串转换为“C”。简而言之,它之所以有效,是因为我可以控制 ToString() 方法。在 BCL 十进制类型上,我无法控制 ToString() 方法。我也不想制作自定义小数类型。
最佳答案
我认为您可以自定义标准格式的输出方式,但不能实现新的标准格式字符。
class Program
{
static void Main(string[] args)
{
decimal cash = 3124.728m;
Console.WriteLine("Result: {0}", cash.ToString("C",
new MoneyFormatInfo("JPY", new System.Globalization.CultureInfo("fr-FR"))));
}
}
class MoneyFormatInfo : IFormatProvider
{
System.Globalization.NumberFormatInfo numberFormat;
public MoneyFormatInfo(string currencyCode, System.Globalization.CultureInfo culture)
{
numberFormat = culture.NumberFormat;
numberFormat.CurrencySymbol = currencyCode;
}
public object GetFormat(Type formatType)
{
return numberFormat;
}
}
请注意,您仍然会使用“C”格式代码来格式化货币值,但您可以通过格式提供程序控制货币符号。
关于c# - 将自定义格式字符串添加到可用的标准字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27906804/