拳击,非拳击和类型转换有什么区别 [英] what is the difference between Boxing,Un-Boxing and typecasting
问题描述
类型转换与装箱有什么主要区别,拆箱?
What are the main differences between typecasting and boxing ,unboxing??
推荐答案
类型转换是表达式到给定类型的转换,前提是类型是相互衍生,或存在合适的转换方法。例如,整数值可以转换为double,反之亦然:
Typecasting is a conversion of an expression to a given type, provided that the types are derived from each other, or a suitable conversion method exists. For example, an integer value can be cast to a double, and vice versa:
int i = 999;
double d = 123.456;
i = (int) d;
d = i; // Implicit cast
或
Or
private void myButton_Click(object sender, EventArgs e)
{
if (sender is Button)
{
Button b = (Button) sender;
}
}
或
Or
foreach (Control c in Controls)
{
if (c is TextBox)
{
TextBox tb = (TextBox) c;
}
}
您无法使用强制转换在没有定义转换或关系的类型之间进行更改。
装箱和拆箱是透明地在Reference类型中包含Value类型(例如整数或结构)的过程,以便它可以用作参考。这有点难以解释,所以看看这里:使用struct和class - 那是什么呢? [ ^ ] - 有一个关于拳击的部分以及它是什么/为什么必要。
You cannot use casting to change between types where there is no defined conversion or relationship.
Boxing and unboxing are the process of "containing" a Value type (such as a integer, or struct) within a Reference type transparently so that it can be used as a reference. This is a bit complicated to explain, so have a look here: Using struct and class - what's that all about?[^] - there is a section on Boxing and what / why it is neccessary.
这篇关于拳击,非拳击和类型转换有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!