类型安全
类型安全:
类型安全是有关类型操作的一种规范。 这一规范限制了不同类型的数据之间的相互转化。类型安全是CLR重要特性之一,在运行时CLR总是知道一个对象的类型。在c#中可以调用GetType()方法来返回引用的对象的类型。GetType()方法定义在超类System.Object中,并且是非虚方法,因此任何类型都不能重写此方法来篡改类型或伪装成另一种类型。
类型安全是CLR最重要的特性之一,在运行时,CLR总是确定一个对象的类型。在C#中可以调用GetType()来返回调用对象的类型,并且由于GetType()继承于System.Object对象,并且为非虚的方法,因此一个类型不可能通过重写此方法而伪装成另一种类型。
(C# 是在编译时静态类型化的,因此变量在声明后就无法再次声明,或者无法用于存储其他类型的值,除非该类型可以转换为变量的类型。MSDN)
强制转化和类型转换
1.隐式转换:隐式转换要求转换必须是类型安全的,不会导致数据丢失,不需要特殊的转换字符。例如从较小的整数类型到较大的整数类型的转换,以及派生类到基类之间的转换。都视作安全的类型转换。
2.显示转换:显示转化也叫强制转换,必须要有强制转换运算符,并且目标变量类型和源变量类型必须是兼容的,但仍然存在数据丢失的风险,例如double 到int的转换,派生类到基类的转换
下面看一个例子,类关系图如下
1.派生类向基类的隐式转换
IBreathe human;
Person person1;
Person person2;
Student student1 = new Student();
Staff staff1 = new Staff();
person1 = student1;//Correct
person2 = staff1;//Correct
2.基类向派生类的转换
IBreathe human;
Person person1;
Person person2;
Student student1 = new Student();
Staff staff1 = new Staff();
person1 = student1;//Correct
person2 = staff1;//Correct
Student student3 = person1;//Compilation Error,需要显示转换,并不能确定person1引用的对象是Student类型
student3 = person2;//Compilation Error,同样需要显示转换,并不能确定person1引用的对象是Student类型
更改代码
Student student3 = (Student)person1;
student3 = (Student)person2;
重新编译通过,运行程序出现运行时错误,抛出InvalidCastException 异常。person2变量虽然是Person类型的但它实际指向的对象的类型确是Staff类型的,Staff和Student两个类都继承自Person,却并不兼容,由于CLR的类型安全特性,拒绝Student类型的变量引用一个Staff类型的对象。
以下是例子中使用到的类代码
public interface IBreathe {
void Breathing();
}
public class Person:IBreathe
{
public void Breathing()
{
Console.Write("Breathing");
}
public void Eat(){
Console.Write("Eeating");
}
public void Sleep()
{
Console.Write("Sleeping");
}
}
public class Student:Person
{
public void Study()
{
Console.Write("Studying");
}
}
public class Staff:Person
{
public void Work()
{
Console.Write("Working");
}
}
浙公网安备 33010602011771号