指定的默认​​格式Decimal.ToString的()方法格式、方法、Decimal、ToString

2023-09-06 10:51:37 作者:桀骜不羁

我有很多电话应用程序 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));
    }
}
 

解决方案

从理论上讲,如果你改变 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.