C# 中转换的几种方式

1):常规的在变量前面加括号进行转换

如:string num ="1";====>转换:int newNum=(int)num;

 

2):使用类型.parse 的方式进行转换

如:string num ="2";=====>转换:int  newNum=int.parse(num);  ps:这里只能是其他类型对string类型的转换,也就是不能  string.parse();

 

3):比较强制的转换,使用Convert进行转换

如:string num="3";=====>转换:int newNum=Convert.toInt32(num);  ps:这里要转换成什么类型就to什么类型,比如“toSingle”、“toDouble”、“toDateTime”  etc

 

4):试探性转换,使用tryParse进行转换

如:

string s = "100";
int result;
if(int.TryParse(s, out result))
{
    Console.WriteLine(result);  //<--执行这句 
}
else
{
    Console.WriteLine("转换失败!");    
}

最后一种有个好处,如果转换成功,则返回  true,失败 返回  false,方便用户进行判断,以便后面的操作。

  

posted on 2018-06-13 14:18  尘世辣么美  阅读(297)  评论(0编辑  收藏  举报

导航