gre*_*b64 5 .net c# formatting string-formatting iformatprovider
我有以下两行代码:
var BadResult = (100).ToString("B", new CustomFormatter ());
var GoodResult = String.Format("{0}", 100, new CustomFormatter ());
Run Code Online (Sandbox Code Playgroud)
然而,BadResult显然很糟糕,GoodResult很好.我的CustomFormatter类声明如下:(同样,我认为一个函数是相关的):
public class CustomFormatter
: IFormatProvider, ICustomFormatter
{
public virtual Object GetFormat(Type formatType)
{
String formatTypeName = formatType.ToString();
formatTypeName = formatTypeName;
Object formatter = null;
if (formatType == typeof(ICustomFormatter))
formatter = this;
return formatter;
}
}
Run Code Online (Sandbox Code Playgroud)
问题本身,当我运行具有"良好结果"的代码行时,GetFormat函数是requestng一个CustomFormatter的实例.
每当用Float.Tostring()调用它时,它期望一个NumberFormatInfo的实例.
我最初跳到"我的CustomFormatter应该从NumberFormatInfo派生".不幸的是,课程是密封的.
那么: 我需要做什么才能用自定义格式化程序调用Float.ToString()?
谢谢!
我不确定您是否可以将自定义格式化程序与 Number.ToString 一起使用。我见过的所有使用自定义格式化程序的示例都使用 String.Format(例如 MSDN 上的)。
我建议你尝试一种扩展方法:
public static class MyExt
{
public static string ToFormattedString(this float This, string format, IFormatProvider provider)
{
return String.Format(provider,"{0}", new object[] {This});
}
}
//now this works
var NoLongerBadResult = (100F).ToFormattedString("B", new CustomFormatter ());
Run Code Online (Sandbox Code Playgroud)
编辑好的,我想我明白了。您需要更改当前的 NumberFormatInfo 并从 GetFormat 返回它:
public class CustomFormatter : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else if(formatType == typeof(NumberFormatInfo))
{
NumberFormatInfo nfi = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone(); // create a copy of the current NumberFormatInfo
nfi.CurrencySymbol = "Foo"; // change the currency symbol to "Foo" (for instance)
return nfi; // and return our clone
}
else
return null;
}
public string Format(string fmt, object arg, IFormatProvider formatProvider)
{
return "test";
}
}
Run Code Online (Sandbox Code Playgroud)
现在这有效:
var NowItWorks = (100).ToString("C", new CustomFormatter ());
var GoodResult = String.Format(new CustomFormatter (),"{0}", 100);
Console.WriteLine(NowItWorks); // Foo 100.00
Console.WriteLine(GoodResult); // test
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1404 次 |
最近记录: |