Programmers find it frequently necessary to cast an object from one type to another. Your programming language of choice decides how easy to expose casting operations to the developer. For example, C# doesn't require any special syntax to cast a type to any of its base types. However, C# does require that the developer explicitly cast a type to any of its derived types. The code below demonstrates:
The text above discusses what is necessary for your compiler of choice to compile your code. We will now discuss what happens at runtime.
At runtime, the CLR always checks casting operations to ensure that casts are always to the object's actual type or any of its base types. For example, the code below will throw an InvalidCastException at runtime:
In the Main method above, a MyType object is constructed and this object is passed to SomeMethod. For example, calling SomeMethod is OK, since MyType is derived from Object which is what SomeMethod expects. Once inside SomeMethod, the CLR verifies that o refers to an object that is either a MyType or a type that is derived from MyType. Since MyType is a MyType, the CLR performs the cast and allows SomeMethod to continue executing.
After SomeMethod returns, the Main function constructs a DateTime object and passes it to SomeMethod. Again, a DateTime is derived from Object so the compiler compiles the code that calls SomeMethod. However, inside SomeMethod, the CLR verifies the cast and detects that o refers to a DateTime object that is not a MyType or any type derived from MyType. At this point, the CLR cannot allow the cast and instead, the CLR throws an InvalidCastException.
If the CLR allowed the cast, then there is no type safety and types could easily spoof other types. Type spoofing is the cause of many security breaches and compromises an application's stability and robustness. Type safety is an extremely important part of the .NET Framework
參考答案:好难啊!