本章包含知识点:
1. 类型转换基础
2. is
和as
的区别
3. 命名空间及其与程序集的关系
4. 代码运行时,运行栈和堆的allocate逻辑,类型相关(主要是继承)调用各类方法(静态,虚,非虚)时对象实例如何找到应该调用的方法
Type conversion
- All types are derived from
System.Object
(like Java), so every object shares a minimum set of behaviors defined bySystem.Object
- CLR requires every object to be created using
new
operator. Things done bynew
:
- Calculate the bytes required by the fields in the class type up to and including
System.Object
. Additional members(type object pointer and sync block index) are also needed to manage the object. - Allocate memory for the object and set all the bytes zero
- Initialize the object’s type object pointer and block index members.
- Constructors called up to
System.Object
- Calculate the bytes required by the fields in the class type up to and including
- One of the most important features of CLR is type safety. You can always know the type of an object by calling
GetType()
. Also, this method is non-virtual so it cannot be overrided. So it can never spoof its type. Conversion to base type is safe so it can be implicitly converted, while conversion to derived type must be explicitly cast. If not, CTE(Compile Time Error). At run time, the CLR checks casting operations to ensure that casts are always to the object’s actual type or any of its base types, that is, if the types are compatible. If not compatible, RTE(Run Time Error).
internal class B{} internal class D : B{} Object o2 = new B(); B b1 = new B(); B b2 = new D(); B b3 = new Object(); // CTE B b4 = d1; D d3 = b2; // CTE D d5 = (D) b2; D d6 = (D) b1; // RTE
is
: checks whether an object is compatible with a given type with the result of evaluation Boolean. It will never throw an exception. Typically, it is used as follows:
if(o is SomeClass){
SomeClass e = (SomeClass) o;
// Use e within the remainder of 'if' statement
}
But in this case, the CLR actually checks the type twice, one atis
and one insideif
s