我学习C#入门的书就是,C# Programming Language,因为是本很经典的书。它仿效C和C++的 经典著作The C Programming Language和C++ Programming Language。这些书的作者都是这门语言的创造者。
最近,发现自己对C#语言的理解有所欠缺,所以又找到了这么C#经典之作,重新温习。发现温故而知新啊。下面我就总结了昨天看的Struct这一章的一些知识。
Struct的声明如下:
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. Struct的this和Class的this有不同的含义
7. 实例字段不允许有初始值
8. Struct不允许声明无参数的实例构造函数
9. Struct不允许声明析构函数
Struct可以实现接口,但不能继承和被继承,不能是抽象的,隐式被声明为sealed,所以abstract和sealed不允许描述struct。因为struct不能继承,所以struct的成员不能是protected和protected internal。函数成员不能是abstract和virtual,而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中是不可以的。