CLR via C# 总结之Chap4 Type Fundamentals

本章包含知识点:
1. 类型转换基础
2. isas的区别
3. 命名空间及其与程序集的关系
4. 代码运行时,运行栈和堆的allocate逻辑,类型相关(主要是继承)调用各类方法(静态,虚,非虚)时对象实例如何找到应该调用的方法

Type conversion
  1. All types are derived from System.Object(like Java), so every object shares a minimum set of behaviors defined by System.Object
  2. CLR requires every object to be created using new operator. Things done by new:
    1. 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.
    2. Allocate memory for the object and set all the bytes zero
    3. Initialize the object’s type object pointer and block index members.
    4. Constructors called up to System.Object
  3. 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.
  4. 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
  5. 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 at is and one inside if s
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值