在C#中TryParse是将一个string类型转换成int类型.
转换失败会返回0.
我们可以通过以下代码来理解如何使用TryParse
using System;
class Parse
{
static void Main()
{
string strnumber = "123";
int result = 0;
bool success = int.TryParse(strnumber, out result);
if (success)
{
Console.WriteLine(result);
}
else
{
Console.WriteLine("Please enter a valid value");
}
}
}
输出
123
using System;
class Parse
{
static void Main()
{
string strnumber = "abc";
int result = 0;
bool success = int.TryParse(strnumber, out result);
if (success)
{
Console.WriteLine(result);
}
else
{
Console.WriteLine("Please enter a valid value");
}
}
}
输出
Please enter a valid value