对于字符串数据类型C#扩展方法 [英] C# Extension Method for String Data Type
问题描述
我和需要被转换成数字很多字符串的Web应用程序处理 - 用户经常把逗号,单位(如厘米,M,G,公斤),货币符号在这些领域的所以我想要做的就是创建一个。,最多清洗现场,并将其转换为十进制字符串扩展方法
例如:
十进制为mynumber =十五CM.ToDecimal();
您期望的用户不同的文化来使用你的申请?如果是的话,最好在用户的区域设置系数:
静态十进制ToDecimal(此字符串str)
{
返回Decimal.Parse(STR,CultureInfo.CurrentCulture);
}
或者你可以替换str中的每一个字符不是一个数字或 CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator
值,然后分析它为十进制
编辑:结果
人们普遍接受的扩展方法应该有自己的命名空间。这将避免命名冲突,迫使最终用户有选择性地导入所需要的扩展。
My web application deals with strings that need to be converted to numbers a lot - users often put commas, units (like cm, m, g, kg) and currency symbols in these fields so what I want to do is create a string extension method that cleans the field up and converts it to a decimal.
For example:
decimal myNumber = "15 cm".ToDecimal();
Are you expecting users of different 'cultures' to use your application? If so it's better to factor in the user's regional settings:
static decimal ToDecimal(this string str)
{
return Decimal.Parse(str, CultureInfo.CurrentCulture);
}
Or you could replace every character in str that isn't a digit or the CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator
value and then parse it as a decimal.
EDIT:
It is generally accepted that extension methods should have their own namespace. This will avoid naming conflicts and force the end user to selectively import the extensions they need.
这篇关于对于字符串数据类型C#扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!