Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将字符串转换为int并在C中测试成功#_C#_String_Parsing_Int - Fatal编程技术网

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

C# 将字符串转换为int并在C中测试成功#,c#,string,parsing,int,C#,String,Parsing,Int,如何检查字符串是否可转换为整数? 假设我们有像“House”、“50”、“Dog”、“45.99”这样的数据,我想知道我是应该只使用字符串,还是使用解析的int值 在JavaScript中,我们有这个函数。如果无法解析字符串,它将返回NaNInt32.TryParse(字符串,Int32)- Int.TryParse将TryParse直接运行到if中,是否可以让它更优雅一点 像这样: if (Int32.TryParse(value, out number)) Console.Wr

如何检查字符串是否可转换为整数?

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

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

Int32.TryParse(字符串,Int32)
-


Int.TryParse

将TryParse直接运行到if中,是否可以让它更优雅一点

像这样:

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

在其中一个搜索结果中找到:

添加此选项是因为我以前看到的答案没有使用价值:

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

这里的
“123”
可以是类似字符串
s=“123”
,OP正在测试该字符串,如果发现该值是数字,则调用后该值
n
将有一个值(
123
)。

我一直在编辑它,因此任何错误都可能已纠正,它返回一个值,指示转换是否成功。谢谢+1我喜欢这个解决方案,但如果将它直接运行到if语句中,它可能会更优雅一些。
int n;
bool isNumeric = int.TryParse("123", out n);