1、数据会变小则必须使用显示转换
1)
double a = 100;
int b =(int) a;
2)字符串转数值,parse
string a = "100";
int b =int.Parse (a);转换失败会抛异常
3)字符串转数值,tryparse
string a = "100";
int b;
bool isConvertSuccess = int.TryParse(a, out b);//转换失败不会抛异常
4)非字符串类型转字符串
4.1非自定义类型
int aa = 100;
string bb = aa.ToString();
Console.WriteLine(bb);
输出
100
4.2自定义类型
class Student
{
public int Age { get; set; }
public string Name { get; set; }
}
Student student = new Student() { Age =15,Name="小李"};
Console.WriteLine(student.ToString ());
输出
Test.Student
对于自定义类型,tostring直接输出了类型的名称,而不是类型的值,所以要想输出类型的值,则需要重写tostring方法,如下:
class Student
{
public int Age { get; set; }
public string Name { get; set; }
public override string ToString()
{
return $"{Age}:{Name }";
}
}
输出
15:小李
5)一种数据类型转另一种数据类型
string a = "100";
int b = Convert.ToInt32(a);
2、数据不会变小,则为隐式转换,当然也可以显示转换
int a = 100;
double b = a;