简体   繁体   English

是否可以让 Convert.ChangeType() 接受货币?

[英]Is it possible to make Convert.ChangeType() accept currency?

NumberFormatInfo nfi = new NumberFormatInfo();
nfi.CurrencySymbol = "$";

var result1 = decimal.Parse("$123456", NumberStyles.Any, nfi).Dump(); // this works well
var result2 = Convert.ChangeType("$123456", typeof(decimal), nfi); // this doesn't work

I need Convert.ChangeType() to accept currency, is it possible?我需要 Convert.ChangeType() 来接受货币,这可能吗? Tried setting NumberFormatInfo but looks like it ignores currency values.尝试设置 NumberFormatInfo,但看起来它忽略了货币值。

Convert is a static class and also ChangeType() is a static method, so you can not override them. Convert是一个静态类,而ChangeType()也是一个静态方法,因此您不能覆盖它们。

Even if this is not exactly what you have asked for, however, you may create your own class change the way you want it to work for decimal (and any others) and use Convert.ChangeType() as default for other types:但是,即使这不是您所要求的,您也可以创建自己的类,更改您希望它为十进制(和任何其他类型)工作的方式,并使用Convert.ChangeType()作为其他类型的默认值:

public static class MyConvert 
{
     public static object? ChangeType(object? value, Type conversionType, IFormatProvider provider)
     {
         if (conversionType == typeof(decimal))
             return decimal.Parse(value.ToString(), NumberStyles.Any, provider);
         else
             return Convert.ChangeType(value, conversionType, provider);
     }
} 

Now the following code would work as you expect:现在,以下代码将按您的预期工作:

var result2 = MyConvert.ChangeType("$123456", typeof(decimal), nfi);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM