Rob*_*cks 36 c# string int parsing
如何检查字符串是否可以转换为int?
假设我们有"House","50","Dog","45.99"这样的数据,我想知道我是应该只使用字符串还是使用解析的int值.
在JavaScript中我们有这个parseInt()函数.如果无法解析字符串,它将返回NaN.
Joh*_*lan 71
Int32.TryParse(String, Int32)- http://msdn.microsoft.com/en-us/library/f02979c7.aspx
bool result = Int32.TryParse(value, out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
Run Code Online (Sandbox Code Playgroud)
Ben*_*ter 12
你可以通过将tryparse运行到if中来使它更优雅吗?
像这样:
if (Int32.TryParse(value, out number))
Console.WriteLine("Converted '{0}' to {1}.", value, number);
Run Code Online (Sandbox Code Playgroud)