FunctionGHW

立志成为真正程序员的码农,伪全栈,目前主要写C#

C#中值类型的装箱(boxing)和拆箱(unboxing)

FunctionGHW posted @ 2014年3月17日 17:57 in C#与.Net with tags c# 装箱 boxing 拆箱 unboxing , 4887 阅读

在C#中,把一个值类型转化成引用类型的过程称为装箱(boxing)。这个引用类型可以是object类型,也可以是此值类型实现的任何接口类型。

        int num = 5;
        //引起装箱操作
        object o = num;
        

CLR会把值类型包装在一个对象内部。装箱的过程大致如下:

  1. 像创建其他引用类型的实例一样,在托管堆上为新对象分配需要的内存。
  2. 将值类型的字段值复制到新对象的对应字段。
  3. 返回这个对象的引用。

拆箱(Unboxing)的过程简单些。拆箱就是从一个装箱后的对象里获得一个指针的过程,这个指针指向该对象中的值类型的字段。拆箱之后往往都伴随着字段的复制(比如赋值操作):

        int val = (int)o;
        

现在大家基本上都是说装箱/拆箱机制的缺点,其缺点至少有:

  • 装箱拆箱都需要额外的计算,影响性能。
  • 装箱需要消耗的托管堆内存,如果有大量的对象产生,会增加GC的压力。
  • 增加代码中强制类型转换操作的次数,增加出错的可能性。

一句话,装箱/拆箱操作对程序的运行速度和内存消耗都很不利,应该尽量避免

既然如此,这个机制为什么还要存在呢?所谓引用类型变量,其实是在线程栈上存放一个引用, 引用指向托管堆上的某个对象。假设这样一个场景,有一个方法的一个参数的类型是object, 也就是对任何类型都通用,object是引用类型,所以调用时就需要传递一个引用。 值类型也是object的分支,所以值类型也可以作为object才对,但是值类型的值是在线程栈上的, 因此为了保证代码能正常工作,就需要把这个值类型"放"到堆上,变成引用类型。

这样看来,所有含有object类型的参数的方法, 都存在引起装箱操作的可能。例如:

        ArrayList ary_lst = new ArrayList();
        ary_lst.Add(2014);// Add(object), 引起装箱
        

感觉上面的示例太过鸡肋,我们换一个。字符串的拼接操作大家用的很多吧, 估计有很多人和我一样随手就用起来了。

        int num = 5;
        string str = "the number is" + num;
        

连接操作会调用System.String.Concat()方法, 最匹配的一个重载是Concat(object, object)num是值类型,因此引起装箱操作,然后Concat方法内部会调用两个对象的ToString()方法,得到两个string,最后调用另一个重载方法Concat(string, string)。装箱操作所产生的"临时对象",对我们一点用也没有, 我们只是想要字符串"5"而已,所以可以这样做:

        int num = 5;
        //不会引起装箱
        string str = "the number is" + num.ToString();
        

因为操作数都是sting类型, 所以会直接调用Concat(string, string),既没有引起不必要的装箱,又少拐了一个弯。

String.Format()方法也存在这样的问题。

        //会引起装箱
        string str2 = string.Format("The number is {0}", 9);
        //不会引起装箱
        string str3 = string.Format("The number is {0}", 9.ToString());
        

 

Liwovosa 说:
2021年4月12日 23:30

If you set out to make me think today; mission accomplished! I really like your writing style and how you express your ideas. Thank you. 123movies websites

Liwovosa 说:
2021年4月13日 19:39

Interesting and amazing how your post is! It Is Useful and helpful for me That I like it very much, and I am looking forward to Hearing from your next.. online casino

SmithSeo 说:
2021年4月17日 17:17

Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking. A Different Version

SmithSeo 说:
2021年4月17日 17:18

An interesting dialogue is price comment. I feel that it is best to write more on this matter, it may not be a taboo topic however usually individuals are not enough to talk on such topics. To the next. Cheers. nama nama situs judi slot online

SmithSeo 说:
2021年4月19日 05:56

You completed a few fine points there. I did a search on the subject and found nearly all persons will go along with with your blog. Training Canberra

jackjohnny 说:
2021年6月02日 16:29

Thank you because you have been willing to share information with us. we will always appreciate all you have done here because I know you are very concerned with our. indian visa online

johnyking 说:
2021年6月16日 18:58

If you set out to make me think today; mission accomplished! I really like your writing style and how you express your ideas. Thank you. 먹튀검증

jackjohnny 说:
2021年6月17日 22:18

Thank you again for all the knowledge you distribute, Good post. I was very interested in the article, it's quite inspiring I should admit. I like visiting you site since I always come across interesting articles like this one. Great Job, I greatly appreciate that. Do Keep sharing! Regards, <a href="https://totogle.com/">먹튀검증</a>

eyeshadow 说:
2021年6月25日 18:46

I personally use them exclusively high-quality elements : you will notice these folks during:

jackjohnny 说:
2021年6月26日 21:31

We have sell some products of different custom boxes.it is very useful and very low price please visits this site thanks and please share this post with your friends. 토토사이트

jackjohnny 说:
2021年6月27日 17:05

I am impressed. I don't think Ive met anyone who knows as much about this subject as you do. You are truly well informed and very intelligent. You wrote something that people could understand and made the subject intriguing for everyone. Really, great blog you have got here. Paypal SMM panel

jackjohnny 说:
2021年6月28日 16:24

We are really grateful for your blog post. You will find a lot of approaches after visiting your post. I was exactly searching for. Thanks for such post and please keep it up. Great work. voyance telephone gaia

jackjohnny 说:
2021年6月29日 18:14

hi was just seeing if you minded a comment. i like your website and the thme you picked is super. I will be back. indian visa on arrival

jackjohnny 说:
2021年7月05日 18:45

Very informative post! There is a lot of information here that can help any business get started with a successful social networking campaign. สล็อต

jackjohnny 说:
2021年7月11日 17:37

This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free. 토토사이트

jackjohnny 说:
2021年7月13日 19:15

this is really nice to read..informative post is very good to read..thanks a lot! Brawl Stars Hack 2021

jackjohnny 说:
2021年7月14日 22:44

ikinci el cikma enjektör bosch kullanilmis oto enjektör satin al ikinci el enjektör

johnyking 说:
2021年7月15日 23:14

Pretty nice post. I just stumbled upon your weblog and wanted to say that I have really enjoyed browsing your blog posts. After all I’ll be subscribing to your feed and I hope you write again soon! scarlett johansson body measurements

Rafay 说:
2021年8月09日 04:29

Https://www.propassion.net

Website hosting bh

johnyking 说:
2021年8月21日 20:29

All the contents you mentioned in post is too good and can be very useful. I will keep it in mind, thanks for sharing the information keep updating, looking forward for more posts.Thanks 먹튀폴리스

johnyking 说:
2021年8月30日 00:08

I really thank you for the valuable info on this great subject and look forward to more great posts. Thanks a lot for enjoying this beauty article with me. I am appreciating it very much! Looking forward to another great article. Good luck to the author! All the best! Search Websites

johnyking 说:
2021年9月14日 15:38

Thanks for the nice blog. It was very useful for me. I'm happy I found this blog. Thank you for sharing with us,I too always learn something new from your post. Sexy baccarat

johnyking 说:
2021年9月15日 16:55

This article was written by a real thinking writer without a doubt. I agree many of the with the solid points made by the writer. I’ll be back day in and day for further new updates. Pkv Games

johnyking 说:
2021年9月16日 02:22

Please let me know if you’re looking for a article writer for your site. You have some really great posts and I feel I would be a good asset. If you ever want to take some of the load off, I’d absolutely love to write some material for your blog in exchange for a link back to mine. Please send me an email if interested. Thank you! Animefenix

johnyking 说:
2021年9月16日 19:06

Cool stuff you have got and you keep update all of us. บาคาร่า-บิกินี่

johnyking 说:
2021年10月06日 23:29

This particular papers fabulous, and My spouse and i enjoy each of the perform that you have placed into this. I’m sure that you will be making a really useful place. I has been additionally pleased. Good perform! how to sell merchant processing

johnyking 说:
2021年10月07日 03:08

Thanks for sharing us. SEO LIMA

johnyking 说:
2021年10月07日 13:17

Excellent and very exciting site. Love to watch. Keep Rocking. AGENCIA SEO

johnyking 说:
2021年10月07日 23:20

Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post. North American Bancard Agent

johnyking 说:
2021年10月08日 18:54 Thank you because you have been willing to share information with us. we will always appreciate all you have done here because I know you are very concerned with our. how to sell credit card processing
johnyking 说:
2021年10月18日 02:33

I would like to say that this blog really convinced me to do it! Thanks, very good post. เคดิตฟรี ยืนยันเบอร์

johnyking 说:
2021年10月19日 23:42 I recently found many useful information in your website especially this blog page. Among the lots of comments on your articles. Thanks for sharing. esteroides
johnyking 说:
2021年10月28日 23:43 I am definitely enjoying your website. You definitely have some great insight and great stories. naza
johnyking 说:
2021年12月13日 21:22

Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info. Hole in One Insurance

johnyking 说:
2021年12月21日 19:14 Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking. podcast transcription service
johnyking 说:
2021年12月21日 19:14 Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking. podcast transcription service
pg slot ทดลองเล่น 说:
2022年3月10日 08:20

I see some amazingly important and kept up to length of your strength searching for in your on the site

us canada 说:
2022年4月09日 08:06

It was a very good post indeed. I thoroughly enjoyed reading it in my lunch time. Will surely come and visit this blog more often. Thanks for sharing.

asia99th 说:
2022年5月09日 07:12

Very nice blog and articles. I am realy very happy to visit your blog. Now I am found which I actually want. I check your blog everyday and try to learn something from your blog. Thank you and waiting for your new post. asia99th

johnyking 说:
2022年5月11日 03:14 This article was written by a real thinking writer. I agree many of the with the solid points made by the writer. I’ll be back. Slim N Lift For Men in Pakistan
เว็บพนันออนไลน์ 说:
2022年5月13日 09:39

Hi! This is my first visit to your blog! We are a team of volunteers and new initiatives in the same niche. Blog gave us useful information to work. You have done an amazing job! เว็บพนันออนไลน์

johny 说:
2022年6月24日 22:22

Thank you because you have been willing to share information with us. we will always appreciate all you have done here because I know you are very concerned with our. Auto Miner 1.19

johny 说:
2022年7月29日 18:59

Wow! Such an amazing and helpful post this is. I really really love it. It's so good and so awesome. I am just amazed. I hope that you continue to do your work like this in the future also keto x3

johny 说:
2022年8月03日 19:48 I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post. Arctos Portable Ac Review
johny 说:
2022年8月03日 22:39 A very awesome blog post. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. viaketo gummies
JDC Result Barisal 说:
2022年8月31日 16:08

In the Bangladesh Education System, Barisal board has a good record and the Barisal Division also successfully completed JSC and JDC terminal examination tests 2022 as per schedules along with all other educational boards of the country, JDC Result Barisal and there are a huge number of general and mass education students have appeared to the Grade 8 final exams from the division.The Bangladesh Secondary and Higher Secondary Education, Barisal Board has successfully completed the Junior Certificate & Junior Dakhil Terminal exams on November like as previous years, and the school education department has to conduct evaluation process through answer sheet corrections for both general and mass education JSC & JDC exam answer sheet to calculate subject wise marks of the student, once the evaluation is completed the JSC Result 2022 Barisal Board is announced with full mark sheet with total CGPA of the student.

johny 说:
2022年9月01日 11:58

This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here keep up the good work glucotrust review

johny 说:
2022年9月01日 13:39

Thanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? I’ve a undertaking that I am simply now operating on, and I have been at the look out for such info. Augusta Precious Metals

johny 说:
2022年9月01日 14:46

Positive site, where did u come up with the information on this posting? I'm pleased I discovered it though, ill be checking back soon to find out what additional posts you include. Birch Gold reviews

johny 说:
2022年9月01日 18:06

Within this webpage, you'll see the page, you need to understand this data. How Many Views To Start Making Money on Youtube

Haryana Board Questi 说:
2022年9月03日 15:32

Haryana Board Model Paper 2023 Class 3 Pdf Download with Answers for English Medium, Hindi Medium, Urdu Medium & Students for Small Answers, Long Answer, Very Long Answer Questions, and Essay Type Questions to Term1 & Term2 Exams at official website. Haryana Board Question Paper Class 3 New Exam Scheme or Question Pattern for Sammittive Assignment Exams (SA1 & SA2): Very Long Answer (VLA), Long Answer (LA), Small Answer (SA), Very Small Answer (VSA), Single Answer, Multiple Choice and etc.

johny 说:
2022年9月04日 23:02 Within this webpage, you'll see the page, you need to understand this data. ラブドール
Johny 说:
2022年9月06日 12:04

In this article understand the most important thing, the item will give you a keyword rich link a great useful website page: how to sell credit card processors

Johny 说:
2022年9月07日 22:07

I invite you to the page where see how much we have in common. kissasian sh

johny 说:
2022年9月11日 18:11

Gives you the best website address I know there alone you'll find how easy it is. cell phone blocker

johny 说:
2022年9月15日 22:28

I am always searching online for storys that can accommodate me. There is obviously a multiple to understand about this. I feel you made few salubrious points in Attributes moreover. Detain busy, awesome career! merchant services training

AP SSC History Model 说:
2022年9月15日 23:01

History can guide learners to see trends and processes from a broader, holistic perspective and to understand them. Through History, they come into contact with other cultures and societies and in this way they gain a more holistic understanding of the contemporary world and their place in this broader context. Telugu Medium, AP SSC History Model Paper English Medium & Urdu Medium Students of the State Board can download the AP 10th History Model Paper 2023 Pdf with Answers designed based on the revised syllabus and curriculum of the course. Class teachers and leading institutional experts are designed and suggested the Part-A, Part-B, Part-C, and Part-D exams like SA-1, SA-2, FA-1, FA-2, FA-3, FA-4 along with Assignments.

johny 说:
2022年9月18日 13:55

I am always searching online for storys that can accommodate me. There is obviously a multiple to understand about this. I feel you made few salubrious points in Attributes moreover. Detain busy, awesome career! mid century glass

johny 说:
2022年9月24日 21:41

Acknowledges for penmanship such a worthy column, I stumbled beside your blog besides predict a handful advise. I want your tone of manuscript... baywind residences

johny 说:
2022年9月24日 21:45

I've proper selected to build a blog, which I hold been deficient to do for a during. Acknowledges for this inform, it's really serviceable! baywind residences

johny 说:
2022年9月27日 03:50

Hmm… I interpret blogs on a analogous issue, however i never visited your blog. I added it to populars also i’ll be your faithful primer. تصليح طباخات

johny 说:
2022年9月27日 13:22

I read this article. I think You put a lot of effort to create this article. I appreciate your work. couvreur 77

johny 说:
2022年9月28日 22:53

Within this webpage, you'll see the page, you need to understand this data. mid century glass

johny 说:
2022年9月30日 00:32

I have a similar interest this is my page read everything carefully and let me know what you think. mid century glass

RAHEEL 说:
2023年2月07日 02:32

Truth be told there you will have without the need of fee, perspective the earliest with the majority of points. 안전슬롯

David 说:
2023年3月15日 02:21

A <a href="https://evisastoindia.org/">visa for India</a> is a document issued by the Indian government that allows foreign nationals to enter, exit, and stay in India for a specific period of time.

David 说:
2023年3月15日 02:22

A <a href="https://evisastoindia.org/">visa for India</a> is a document issued by the Indian government that allows foreign nationals to enter, exit, and stay in India for a specific period of time.

Indian Visa for US C 说:
2023年4月24日 20:38

US citizens traveling to India are required to obtain a visa prior to their trip. The Indian visa application process requires submitting personal information, passport details, and itinerary plans. Visas can be obtained from the Indian embassy or consulate in the US, or through an online application process.

Emergency visa to In 说:
2023年4月28日 16:45

"eVisas to India specialize in providing hassle-free visa services to individuals who are looking to travel to india. Our team of experienced professionals in dedicated to helping you obtain the necessary documentation for your trip, whether it’s emergency visa, tourist visa, or business visa.
Whether you need to travel to India urgently or plan a leisure trip, we can help you obtain the appropriate visa quickly and efficiently. Our goal is to provide you with a stress-free experience so that you can focus on your trip without worrying about the visa process.
Contact us today to learn more about our services and how we can help you obtain your visa to India."

Business coaching ke 说:
2023年7月10日 21:53

The blog section on this site is my favorite. The articles are well-written and cover a wide range of interesting topics.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter