您的位置:首页 > 编程语言 > C#

C# struct 与class 使用 new 关键字的区别

2016-05-07 16:48 477 查看
31down
vote
Why are we not forced to instantiate a struct with "new", like when using a class?

When you "new" a reference type, three things happen. First, the memory manager allocates space from long term storage. Second, a reference to that space is passed to the
constructor, which initializes the instance. Third, that reference is passed back to the caller.

When you "new" a value type, three things happen. First, the memory manager allocates space from short term storage. Second, the constructor is passed a reference to the
short term storage location. After the constructor runs, the value that was in the short-term storage location is copied to the storage location for the value, wherever that happens to be. Remember, variables
of value type store the actual value.

(Note that the compiler is allowed to optimize these three steps into one step if the compiler can determine that doing so never exposes a partially-constructed struct to user code. That is, the compiler can generate code that simply passes a reference to the final storage
location to the constructor, thereby saving one allocation and one copy.)

由上可知,C#中对结构体使用new关键字,先申请一块临时内存,将这块内存的引用传给构造函数,最后将临时内存中的内容复制到值得存储空间中。

即即使使用new关键字,结构体总是值类型。

原文链接


31down
vote
Why are we not forced to instantiate a struct with "new", like when using a class?

When you "new" a reference type, three things happen. First, the memory manager allocates space from long term storage. Second, a reference to that space is passed to
the constructor, which initializes the instance. Third, that reference is passed back to the caller.

When you "new" a value type, three things happen. First, the memory manager allocates space from short term storage. Second, the constructor is passed a reference to
the short term storage location. After the constructor runs, the value that was in the short-term storage location is copied to the storage location for the value, wherever that happens to be. Remember, variables
of value type store the actual value.

(Note that the compiler is allowed to optimize these three steps into one step if the compiler can determine that doing so never exposes a partially-constructed struct to user code. That is, the compiler can generate code that simply passes a reference to the final storage
location to the constructor, thereby saving one allocation and one copy.)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c#