C# Extension Method for String Data Type(字符串数据类型的 C# 扩展方法)
问题描述
我的 Web 应用程序处理需要大量转换为数字的字符串 - 用户经常在这些字段中放置逗号、单位(如 cm、m、g、kg)和货币符号,所以我想做的是创建一个清除字段并将其转换为小数的字符串扩展方法.
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.
例如:
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);
}
或者您可以替换 str 中不是数字或 CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator
值的每个字符,然后将其解析为小数.
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.
人们普遍认为扩展方法应该有自己的命名空间.这将避免命名冲突并强制最终用户有选择地导入他们需要的扩展.
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# 扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:字符串数据类型的 C# 扩展方法


- C# 中多线程网络服务器的模式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01