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# 扩展方法


基础教程推荐
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 如果条件可以为空 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 将数据集转换为列表 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01