ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

C#通过对象拆箱

2019-10-25 01:06:13  阅读:202  来源: 互联网

标签:unboxing casting boxing c


我可以将字节转换为整数,没有任何问题.

byte a = 2;
int b = a;      // => unboxing, boxing or conversion?

当我先将字节转换为对象然后再转换为int时,我得到一个InvalidCastException.

byte a = 2;
object b = a;    // => boxing?
int c = (int) b; // => unboxing fails?

但是我可以通过使用Convert.ToInt32解决此问题.

byte a = 2;
object b = a;                // => boxing?
int c = Convert.ToInt32(b);  // => what happens here?

>为什么在第二个示例中出现InvalidCastException?
>后台的Convert.ToInt32是什么?
>我是否正确标记了装箱,拆箱和转换标签? /如果不确定示例中的正确术语是什么?
>转换运算符在这里吗?是否有关于基本类型的基本转换运算符的概述?

请不要犹豫,向我暗示其他我可能弄错或错过的事情.

解决方法:

Why do I get an InvalidCastException in the second example?

因为您指定要转换(同时取消装箱)(装箱的)变量的类型为其他类型.而且没有定义内置的,隐式的或显式的转换运算符,因此它会失败.

What does Convert.ToInt32 in the background?

This.它使用IConvertible接口进行转换.

Did I label boxing, unboxing and conversion correctly? / What is the correct term when in the examples where I’m not sure?

int b = a;      // => conversion
object b = a;    // => boxing
int c = (int) b; // => casting fails
int c = Convert.ToInt32(b);  // => what happens here: a method call that happens to do a conversion

Are the conversion operators at play here? Is there an overview about the basic conversion operators of the basic types?

是的,尽管在CLR中定义.

标签:unboxing,casting,boxing,c
来源: https://codeday.me/bug/20191025/1924762.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有