[ILDASM Boxing]从进一步了解Struct和Class的不同学到的

1. Struct与类的区别:
(1)结构是值类型,不是引用类型。
(2)结构可以继续接口,但是不可以继承类或结构。
(3)结构的构造方法的工作方式有所不同,只能声明带参数的构造方法,且不能声明析构方法。
(4)可以指定字段如何在内存中布局。

 

(5) 使用。如下两种方法都可以。但是切记:方法一的话,"Users user;" 并没有调用构造函数初始化成员变量!!所以,总起来讲,还是方法二好!以下为MSDN words:

The struct type is suitable for representing lightweight objects such as Point, Rectangle, and Color. Although it is possible to represent a point as a class, a struct is more efficient in some scenarios. For example, if you declare an array of 1000 Point objects, you will allocate additional memory for referencing each object. In this case, the struct is less expensive.

It is an error to declare a default (parameterless) constructor for a struct. A default constructor is always provided to initialize the struct members to their default values.

It is an error to initialize an instance field in a struct.

When you create a struct object using the new operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the new operator. If you do not use new, the fields will remain unassigned and the object cannot be used until all of the fields are initialized.

There is no inheritance for structs as there is for classes. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Structs, however, inherit from the base class Object. A struct can implement interfaces, and it does that exactly as classes do.

 

方法一:
static void Main()
        {
           
Users user;
            user.UserName = "张三丰";
            user.UserSex = "女";
            user.UserAge = 18;
            user.GetInfo();
        }
方法二:
static void Main()
        {
           
Users user = new Users("张三丰","男",29);
            user.GetInfo();
        }

2. 查看汇编,直接在VS里看Disassembly;查看IL,打开CommandPrompt: ildasm,然后在打开的IL DASM中打开任何.Net的assembly就可以查看Reflection可以看到的东西以及IL的代码。

3. Struct的确只能分配到stack上。但是,别忘了:任何值类型都可以通过boxing变成一个object分配到heap上的。

 

posted @ 2010-08-24 16:08  能巴  阅读(230)  评论(0编辑  收藏  举报