由C语言中可以引申过来,强制类型转换即为”(数据类型)变量”,C#中也可以这样做,但是如果出现将“123abc”转换为int类型时,编译会出错。
c#中可以有以下几种办法:
- int.Parse(i);(或其他.Parse)i为要转换的变量,返回值即为转换结果,但是,当无法转换的情况下,会出现错误。
- Convert.To….各种子函数,可以转换为byte,char,int,unsigned int,string等各种变量,实际调用了int.Parse,与第一种比较,这一种相当于两次调用,不如第一种更高效。
- int.TryParse(s,out m);该函数为最可靠的方法,s为输入的字符串,m为要改变的变量,此处加入out的作用是让该函数可以直接修改m的值。(而不是像C语言中,函数的参数只是用于传递给函数,不能修改传入的参数,只能通过指针的方法来修改)该函数有一个布尔数的返回值,表示是否转换成功。
例如可以观察代码运行现象(每次只用其中一句,其他注释掉)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace shiyan
{
class Program
{
static void Main(string[] args)
{
int i = 0,j=0,m=0,n=0;
bool jieguo;
string str = "123abc";
i = (int)str;
j = Convert.ToInt32(str);
m = int.Parse(str);
jieguo = int.TryParse(str, out n);
}//main函数括号
}
}