指定的默认格式Decimal.ToString的()方法 [英] Specify default format for Decimal.ToString() method
问题描述
我有很多电话应用程序 Decimal.ToString的(无效)一>。默认的格式是不是需要什么。我可以改变这些调用其他 Decimal.ToString的重载,但它会更好,如果我没得。那么,有没有一种方法来指定Decimal.ToString的(无效)格式不同的方法,这样我就不用修改任何调用此方法?
更新
由于回答以下指示,就可以做我想做的,但我不应该这样做,因为它不是良好的编程习惯。有涉及重写调用许多替代办法;我打算去的方法是存储所需的格式为一个字符串常量,它传递给电话:
类示例
{
常量字符串s_DecimalFormat =N2;
私人小数myDecimal1 = 12.345;
私人小数myDecimal2 = 6.7;
公共无效方法()
{
的System.Console.WriteLine(myDecimal1.ToString(s_DecimalFormat));
的System.Console.WriteLine(myDecimal2.ToString(s_DecimalFormat));
}
}
从理论上讲,如果你改变<一href="http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.currentculture(v=vs.110).aspx"相对=nofollow> System.Globalization.CultureInfo.CurrentCulture
的东西,格式化小数你想要的方式,这是可行的。这将打开一个的巨大的可以蠕虫你不想用10英尺极触动。 别这样。更改所有通话。也许写它的方法。
I have an application with a lot of calls to Decimal.ToString(void). The default format is not what is needed. I could change these calls to one of the other Decimal.ToString overloads, but it would be nicer if I didn't have to. So, is there a way to specify a different format for the Decimal.ToString(void) method so that I don't have to modify any of the calls to this method?
Update
As the answer below indicates, it is possible to do what I want, but I should not do so as it is not good programming practice. There are many alternative approaches which involve rewriting the calls; the approach I plan to go with is to store the desired format as a string constant and pass that to the calls:
class Example
{
const string s_DecimalFormat = "N2";
private decimal myDecimal1 = 12.345;
private decimal myDecimal2 = 6.7;
public void Method()
{
System.Console.WriteLine(myDecimal1.ToString(s_DecimalFormat));
System.Console.WriteLine(myDecimal2.ToString(s_DecimalFormat));
}
}
Theoretically, if you change System.Globalization.CultureInfo.CurrentCulture
to something that formats a decimal the way you want, this would work. It will open up a huge can of worms you don't want to touch with a ten-foot pole. Do not do this. Change all your calls. Maybe write a method for it.
这篇关于指定的默认格式Decimal.ToString的()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!