1 #region R#.1 @.net中的隐式、显式转换以及as、is操作符 2 //z 2012-07-16 14:22:19 @IS2120.T2169364049[T1,L65,R1,V259] 3 1. System.Object 4 在.net中,每一个对象最终都会派生自System.Object类型,这意味着下面两种类型定义事实上是一样的: 5 class IS2120{ 6 ... 7 } 8 和 9 class IS2120:System.Object{ 10 ... 11 } 12 既然每个对象最终都会自System.Object派生而来,那么可以保证任一类型的任一个对象都有一个最基本的功 13 能集。 14 15 2. 功能集 16 Equals 判断两个Object是否具有同样的值 17 GetHashCode 对于对象的值返回一个哈希值 18 GetType 返回一个Type-Derived对象,表明当前对象的类型 19 ToString 默认,返回类型名。 20 21 3. new 操作符 22 为创建对象从托管堆中分配空间。并且初始化对象本身数据之外的开销数据成员的值。 23 每个对象都有一些额外的字节,这些字节被clr用来管理对象,比如说object的虚表指针以及一个指向sync 24 block的引用。 25 IS2120 i = new IS2120("cnblogs"); 26 27 new 没有与之对应的诸如delete这样的操作符。在.net (1.0) 中不能显式地释放或是销毁一个对象。 28 .net 提供了gc,用于自动检测不再使用的对象并将之释放。 29 30 4. 数据类型之间的转换 31 4.1 派生类能向基类隐式转换 32 数据类型之间相关转换的规则 33 System.Object o = new IS2120("cnblogs"); 34 这能够顺利的编译和执行,因为进行了一个隐式转换。new操作符返回一个IS2120类型的引用,然后隐式转换 35 为了System.Object类型了。所有从System.Object派生的类型都能转换为System.Object。(派生类能够向基 36 类隐式转换) 37 38 编译器没有提供(不支持)从基类向派生类的转化 39 IS2120 i = o; 40 编译时(vs2008)会出现这样的错误: 41 Error 1 Cannot implicitly convert type 'object' to 'Test.ImplictedCast.IS2120'. 42 An explicit conversion exists (are you missing a cast?) 43 44 加上这样的形式就能够正确编译了 45 IS2120 i = (IS2120)o; 46 这样是使用了一个显示的转换。 47 48 另一个例子 49 System.Object o = new System.Object(); 50 IS2120 i = (IS2120)o; 51 能够正常编译,但是执行的时候会抛出一个异常InvalidCastExceptions was unhandled. 52 Unable to cast object of type 'System.Object' to type 'Test.ImplictedCast.IS2120'. 53 c#的CLR在执行第二句的时候会校验由o所引用的对象是否是一个IS2120类型或是IS2120的派生类型。如是,则 54 允许转换。否则就会抛出异常。 55 56 5. as 操作符,执行转换的另一种方式。 57 IS2120 i = new IS2120(); 58 System.Object o = i as System.Object; 59 试图将一个对象转换为指定类型。不像一般的转换,as操作符不会抛出异常。 60 如果转换没有成功执行,结果将为null。 61 System.Object o = new System.Object(); 62 IS2120 i = o as IS2120; 63 64 i.ToString(); // 由于i为null,那么执行这个会抛出 NullReferenceException 。 65 Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of 66 an object. 67 68 6. is 操作符 69 检查一个object与一个类型是否兼容,并返回评估的结果。该操作符也不抛出异常。 70 System.Object o = new System.Object(); 71 System.Boolean b1 = (o is System.Object); //True 72 System.Boolean b2 = (o is IS2120); // False 73 如果对象引用为null,总是返回 false 。 74 75 7. 练习 76 class B{ 77 int x; 78 } 79 80 class D:B{ 81 int x; 82 } 83 es : execute successfully 84 ce : compiler error 85 re : common language runtime error 86 87 7.1 System.Object o1 = new System.Object(); 88 7.2 System.Object o2 = new B(); 89 7.3 System.Object o3 = new D(); 90 7.4 System.Object o4=o3; 91 7.5 B b1 = new B(); 92 7.6 B b2 = new D(); 93 7.7 D d1 = new D(); 94 7.8 B b3 = new System.Object(); 95 7.9 D d3 = new System.Object(); 96 7.10 B b3 = d1; 97 7.11 D d2 = b2; 98 7.12 d4 = (D)d1; 99 7.13 d5 = (D)b2; 100 7.14 d6 = (D)b1; 101 7.15 b4 = (B)o1; 102 7.16 b5 = (D)b2; 103 #endregion //z 2012-07-16 13:15:51 @IS2120.T31932526 ------------------------------------+
.net中的隐式、显式转换以及as、is操作符
@IS2120#CNBLOGS.T2169364049[T1,L65,R1,V259]:备忘
$ € ₤ ₭ ₪ ₩ ₮ ₦ ₱ ฿ ₡ ₫ ﷼ ¥ ﷼ ₫ ₡ ฿ ₱ ₦ ₮ ₩ ₪ ₭ ₤ € $