在C#中,有许多关于类型转换的问题,比如string转int,int转string 等类型,
我就列举一些简单的类型转换。
int 转 string
int a = 10;
string str = a.ToString();
string str1 = Convert.ToString(a);
int temp = int.Parse(str);
//parse里必须是字符串,如果不知道里面是否 是int型字符串可以用tryParse
float b = float.Parse(str);
string 转int
string str = "123";
int a = Convert.ToInt32(str);
int b = int.Parse(str);
int 转 char
int a = 98; //char 类型的数值一般是由ASCLL码决定, int类型转char , 转的是ASCLL码对应的值
char b = (char)a;
char 转int
char b = 'a';
int a = b;//转成相应ascll码值 a = 97 ;
int 转byte[] 与 byte[] 转int
int s = 100;
//Int 到 Byte数组
byte[] buffer = System.BitConverter.GetBytes(s);
byte b = 30;
int a = b;
//Byte数组到Int int sh = System.BitConverter.ToInt32(buffer, 0);
string 转 char
// string 转换成 Char[]
string ss = "abcdefg";
char[] cc = ss.ToCharArray();
char a = 'a';
string b = a.ToString();
char[] 转string
Char[] 转换成string
string s = new string(cc);
byte[] 和string 互相转
//byte[] 与 string 之间的转换
byte[] bb = Encoding.UTF8.GetBytes(ss);
string s = Encoding.UTF8.GetString(bb);
byte[] 与char[]互转
byte[] buffer;
char[] ch = Encoding.ASCII.GetChars(buffer);
byte[] buffer = Encoding.ASCII.GetBytes(ch);