8.2.4 Type system unification

本文介绍了C#的统一类型系统,所有类型包括值类型都派生自object类型,可对任何值调用object方法。还展示了装箱和拆箱操作,这种统一类型系统让值类型具备对象特性且无额外开销,能弥合值类型和引用类型的差距,使Stack类可用于任何类型元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值