将字符串转换为 int 并在 C# 中测试成功

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/405619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 02:09:17  来源:igfitidea点击:

Convert string to int and test success in C#

c#stringparsingint

提问by TheFlash

How can you check whether a stringis convertibleto an int?

如何检查字符串是否可以转换int?

Let's say we have data like "House", "50", "Dog", "45.99", I want to know whether I should just use the stringor use the parsed intvalue instead.

假设我们有像“House”、“50”、“Dog”、“45.99”这样的数据,我想知道我是应该使用字符串还是使用解析的int值。

In JavaScript we had this parseInt()function. If the string couldn't be parsed, it would get back NaN.

在 JavaScript 中,我们有这个parseInt()函数。如果无法解析字符串,它将返回NaN

采纳答案by Johnno Nolan

Int32.TryParse(String, Int32)- http://msdn.microsoft.com/en-us/library/f02979c7.aspx

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);         
  }

回答by keithwarren7

Int.TryParse

Int.TryParse

回答by BenAlabaster

Could you not make it a little more elegant by running the tryparse right into the if?

通过将 tryparse 直接运行到 if 中,您能不能让它更优雅一点?

Like so:

像这样:

if (Int32.TryParse(value, out number))     
  Console.WriteLine("Converted '{0}' to {1}.", value, number);

回答by Ganesh Kamath - 'Code Frenzy'

found this in one of the search results: How do I identify if a string is a number?

在其中一个搜索结果中找到了这个:How do I identify a string is a number?

Adding this because the answers i saw before did not have usage:

添加这个是因为我之前看到的答案没有使用:

int n;
bool isNumeric = int.TryParse("123", out n);

here "123"can be something like string s = "123"that the OP is testing and the value nwill have a value (123) after the call if it is found to be numeric.

这里"123"可以是类似于s = "123"OP 正在测试的字符串的东西,如果发现它是数字,则该值n123在调用后具有一个值 ( )。