C#基础——类型转换
1. 自动类型转换
//基本数据类型之间的自动类型转换
int i = 10;
double d = i;
//发生自动转换
//引用数据类型之间的自动类型转换
class Person { }
class Student : Person { }
Student stu = new Student();
Person person = stu;
//发生自动转换
2. 强制类型转换
double d = 10;
int i = (int) d;
//发生强制转换,此处会丢失数据精度
//引用数据类型之间的自动类型转换
class Person { }
class Student : Person { }
//Student 继承了Person类
Person person = new Student();
//父类引用指向子类对象
Student stu = (Student)person;
//发生强制转换
//对于引用类型的强制转换还可以是as关键字来实现,如:
Student stu = person as Student;
//发生强制转换
3. 不同类型与string之间的相互转换
1.字符串转换成基本数据类型
int i = int.Parse("10");
double d = double.Parse("10.5");
bool b = bool.Parse("true");
//注:很多初学者一直认为基本数据类型就像和Java一样,
//其实C#的所有基本数据类型都是结构(struct)类型,在
//C#中结构是允许有方法的,所有基本数据类型都有Parse方法
//xx.Parse()只是这种类型转换的一种方式,
//Convert类提供了很多更丰富的类型转换的方法,如:
int i = Convert.ToInt32("10");
bool b = Convert.ToBoolean("true");
DateTime time = Convert.ToDateTime("2000-2-2");
2.将原始值转换成string
//统一用ToString()方法即可
int i = 10;
double d = 10.5;
bool b = false;
string si = i.ToString();
string sd = d.ToString();
string sb = b.ToString();
4. as 类型转换与(xx)类型转换的区别
Student stu = (Student)person;
Student stu = person as Student;
以上两种方式都可实现类型的强制转换,但两者还是有很大的区别,主要有两点:
1. as 只能用在引用数据类型的转换,而(xx)可用在引用类型和值类型
2. as 在类型转换时如果转换不了将返回null值,而(xx)转换不了将直接报出异常(Exception)
C#基础——类型转换
最新推荐文章于 2024-06-15 18:08:35 发布