解析字符串到整数(不惜任何代价水) [英] Parse String to Integer (come hell or high water)
问题描述
我需要保持传统VB.NET Web应用程序。数据类型是,我会说,不一致的。尤其是还有就是有时存储为整数,有时为字符串数据,我必须可靠地解析字符串为整数。如果解析出了问题,应该始终返回0。
I need to maintain a legacy VB.NET web application. Data typing is, I would say, inconsistent. Especially, there are data that is stored sometimes as integers and sometimes as strings, and I have to parse strings to integers reliably. If parsing goes wrong it should always return 0.
问题是,我不能使用任何的.NET / VB.NET解析功能,但我不得不依靠自制的功能。
The problem is, I can't use any of the .NET/VB.NET parsing functions for this, but I have to rely on a self-made function.
我可以用一个班轮标准框架调用做好每串到整数解析任务?
Could I use a one-liner standard framework call to do every String-to-Integer parsing task?
让我们说有一个可以为空,空字符串,包含像10重presentation整数或含有别的东西。
Let's say there is a string that can be null, empty, contain an integer representation like "10" or contain something else.
我曾与一个空,输入字符串尝试这些
CType(string, Integer) -> Conversion from string "" to type 'Integer' is not valid.
Convert.ToInt32(string) -> Input string was not in a correct format.
Integer.Parse(string) -> Input string was not in a correct format.
CInt(string) -> Conversion from string "" to type 'Integer' is not valid.
Val(string) -> Success!
但即使瓦尔可能会失败。该万无一失的方法是调用一个自制的功能:
But even Val can fail. The surefire way is to call a self-made function:
Public Function ToInteger(ByVal s As String) As Integer
s = Trim(s)
Dim i As Integer
Try
i = Val(s)
Catch ex As Exception
i = 0
End Try
Return i
End Function
我觉得这很烂。这是不好的,因为:
I think this sucks. This is bad because:
- 我试图解析字符串为整数!这不是火箭科学,即使语义参与
- 自制标准不沾得非常好。某处在code,你总能找到打破标准框架的解决方案
其结果是有在软件不必要的错误。我指责标准框架这一点。除非,当然更好的解决方案被发现:)
As a result there are unnecessary bugs in the software. And I accuse the standard framework for this. Unless, of course a better solution is found :)
感谢所有的答案。 Int32.TryParse是完美的在这里。
Thanks for all the answers. Int32.TryParse is perfect here.
但是,如果你要输入的第一个转换为字符串,中投可能会失败。一个可能的DBNull值从数据库中读取对象时一样。
But if you have to cast the input to a string first, the cast can fail. Like when reading from a database object with a possible DBNull value.
推荐答案
使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx\"><$c$c>Int32.TryParse$c$c>而忽略了返回值 - 只使用了参数在的值。你所要做的,虽然修剪自己。
Use Int32.TryParse
and ignore the return value - just use the value in the out
parameter. You'll have to do the trimming yourself though.
这篇关于解析字符串到整数(不惜任何代价水)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!