8.2.4 Type system unification

王朝other·作者佚名  2006-01-10
窄屏简体版  字體: |||超大  

8.2.4 Type system unification

C# provides a .unified type system.. All types.including value

types.derive

from the type object. It is

possible to call object methods on any value, even values of

.primitive.

types such as int. The example

using System;

class Test

{

static void Main() {

Console.WriteLine(3.ToString());

}

}

calls the object-defined ToString method on an integer literal,

resulting

in the output .3..

The example

class Test { static void Main() { int i = 123;

object o = i; // boxing

int j = (int) o; // unboxing

}

}

is more interesting. An int value can be converted to object and back again

to int. This example shows

both boxing and unboxing. When a variable of a value type needs to be

converted to a reference type, an

object box is allocated to hold the value, and the value is copied into the

box. Unboxing is just the opposite.

When an object box is cast back to its original value type, the value is

copied out of the box and into the

appropriate storage location.

This type system unification provides value types with the benefits of

object-ness without introducing

unnecessary overhead. For programs that don.t need int values to act like

objects, int values are simply

32-bit values. For programs that need int values to behave like objects,

this capability is available on

demand. This ability to treat value types as objects bridges the gap

between value types and reference types

that exists in most languages. For example, a Stack class can provide Push

and Pop methods that take and

return object values.

public class Stack

{

public object Pop() {.}

public void Push(object o) {.}

}

Because C# has a unified type system, the Stack class can be used with

elements of any type, including

value types like int.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航