C# tryparse 这个转换

来源:百度知道 编辑:UC知道 时间:2024/05/28 10:10:28
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
string[] s ={ "1", "a", "0", "-1", "1.5" };
int result;
foreach(string r in s)
{
int.TryParse(r,out result);
Console.WriteLine(result);
}
Console.ReadLine();
}
}
}
//结果 1,0,0,-1,0
//很纳闷, 为什么1.5就转不了呢? 而且有非数值类型的时候("a"), 有没有一个返回值什么的让我知道类型错误呢?---不要告诉转换为0就是, 这和人家本身就是0的就没有区别了!

if (int.TryParse(r,out result))
Console.WriteLine(result);

public static bool TryParse(
string value,
out bool result
)
参数
value
类型:System..::.String

包含要转换的值的字符串。

result
类型:System..::.Boolean%

如果转换成功,当 value 等于 TrueString 时,此方法返回时将包含 true,当 value 等于 FalseString 时,此方法返回时将包含 false。如果转换失败,则包含 false。如果 value 为 nullNothingnullptrnull 引用(在 Visual Basic 中为 Nothing) 或不等于 TrueString 或 FalseString,则转换将失败。该参数未经初始化即被传递。

返回值
类型:System..::.Boolean

如果 value 成功转换,则为 true;否则为 false。
TryParse 方法类似于 Parse 方法,不同之处在于 TryParse 方法在转换失败时不引发异常。

value 参数的前后可加空格。比较不区分大小写。

因为1.5不是合法的整型

使用double.TryParse就可以转了

可将类型转换写在try-catch里面,抛出错误后在catch中写continue,进行下一轮的for,while循环