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


基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01