Ale*_*lex 59 .net c# string integer
我只是想知道c#语言或.net框架中是否有内置的东西可以测试是否有东西是整数
if (x is an int)
// Do something
Run Code Online (Sandbox Code Playgroud)
在我看来可能有,但我只是一年级编程学生,所以我不知道.
Bra*_*don 145
使用int.TryParse方法.
string x = "42";
int value;
if(int.TryParse(x, out value))
// Do something
Run Code Online (Sandbox Code Playgroud)
如果它成功解析它将返回true,out结果将其值作为整数.
Wil*_*l P 15
我想我记得在int.TryParse和int.Parse Regex和char.IsNumber之间进行性能比较,char.IsNumber最快.无论如何,无论表现如何,这里还有一种方法.
bool isNumeric = true;
foreach (char c in "12345")
{
if (!Char.IsNumber(c))
{
isNumeric = false;
break;
}
}
Run Code Online (Sandbox Code Playgroud)
Geo*_*org 12
对于Wil P解决方案(见上文),您也可以使用LINQ.
var x = "12345";
var isNumeric = !string.IsNullOrEmpty(x) && x.All(Char.IsDigit);
Run Code Online (Sandbox Code Playgroud)
roc*_*hal 11
如果您只想检查传递变量的类型,可以使用:
var a = 2;
if (a is int)
{
//is integer
}
//or:
if (a.GetType() == typeof(int))
{
//is integer
}
Run Code Online (Sandbox Code Playgroud)
如果您只想检查它是否是字符串,可以将“out int”关键字直接放在方法调用中。根据 dotnetperls.com 网站,旧版本的 C# 不允许使用此语法。通过这样做,您可以减少程序的行数。
string x = "text or int";
if (int.TryParse(x, out int output))
{
// Console.WriteLine(x);
// x is an int
// Do something
}
else
{
// x is not an int
}
Run Code Online (Sandbox Code Playgroud)
如果你还想获取int值,可以这样写。
方法一
string x = "text or int";
int value = 0;
if(int.TryParse(x, out value))
{
// x is an int
// Do something
}
else
{
// x is not an int
}
Run Code Online (Sandbox Code Playgroud)
方法2
string x = "text or int";
int num = Convert.ToInt32(x);
Console.WriteLine(num);
Run Code Online (Sandbox Code Playgroud)
参考: https: //www.dotnetperls.com/parse
| 归档时间: |
|
| 查看次数: |
181233 次 |
| 最近记录: |