再读C# Programming Language之结构(struct)

我学习C#入门的书就是,C# Programming Language,因为是本很经典的书。它仿效C和C++的 经典著作The C Programming Language和C++ Programming Language。这些书的作者都是这门语言的创造者。

最近,发现自己对C#语言的理解有所欠缺,所以又找到了这么C#经典之作,重新温习。发现温故而知新啊。下面我就总结了昨天看的Struct这一章的一些知识。

Struct的声明如下:

声明如下:
[Attributes] [new | public | protected | internal | private ] struct Point [ : interface,……]
{    
       constant-declaration
        field-declaration
       method-declaration
       property-declaration
       event-declaration
       indexer-declaration
       operator-declaration
       constructor-declaration
       static-constructor-declaration
       type-declaration
}

Struct Class 的区别:

1.       Struct 是值类型

2.       所有的struct 类型都隐式继承自System.ValueType

3.       Struct类型变量的赋值是得到一个拷贝值

4.       Struct得默认值是其内部字段的初始值:值类型是该值类型的默认值,引用类型是null

5.       Struct类型和对象之间需要装箱和拆箱操作

6.       StructthisClassthis有不同的含义

7.       实例字段不允许有初始值

8.       Struct不允许声明无参数的实例构造函数

9.       Struct不允许声明析构函数

Struct可以实现接口,但不能继承和被继承,不能是抽象的,隐式被声明为sealed,所以abstractsealed不允许描述struct。因为struct不能继承,所以struct的成员不能是protectedprotected internal。函数成员不能是abstractvirtual,override只可以被使用在从System.ValueType继承来的virtual方法上。

System.ValueType里的virtual方法有:

public override bool Equals(object obj);
public override extern int GetHashCode();
public override string ToString();
struct的变量被转换成object或者其实现的接口时,会发生装箱操作。
反之,是拆箱操作。在装箱的过程中,struct的值被拷贝到了装箱的实例中。
所以在连续的装箱和拆箱的过程中,被拆箱的
struct的变化不会引用在箱中的struct的变化。
在这里值得一提的是,我在书中有一段话实在是看不懂,贴在下面,希望有哪位大侠可以帮
我解释一下。
Within an instance constructor of a struct, this corresponds to an out parameter of the struct type, 
and within an instance function member of a struct,
this corresponds to a ref parameter of the struct type.
In both cases, this is classified as a variable,
and it is possible to modify the entire struct for which the
function member was invoked by assigning to this or by passing
this as a ref or out parameter.
还有在Struct的方法中this是可以被赋值的,而Class中是不可以的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值