用例为拳击在C#中的值类型? [英] Use cases for boxing a value type in C#?

查看:110
本文介绍了用例为拳击在C#中的值类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有情况下,当需要被视为引用类型的
实例的
值类型的实例。
为$ B像这样$ b的情况下,值类型
实例可以通过名为拳击
过程中转换成
引用类型实例。当一个价值
类型的实例是盒装,存储在堆上和
实例的值复制到了
分配空间
。此存储的引用是
放置在堆栈中。装箱值
是一个对象,引用类型的
包含值
型实例的内容。

There are cases when an instance of a value type needs to be treated as an instance of a reference type. For situations like this, a value type instance can be converted into a reference type instance through a process called boxing. When a value type instance is boxed, storage is allocated on the heap and the instance's value is copied into that space. A reference to this storage is placed on the stack. The boxed value is an object, a reference type that contains the contents of the value type instance.

了解.NET的通用类型系统

维基百科的存在是Java的例子。但在C#中,什么是某些情况下,人们必须框中输入一个值类型?或将一个更好的/类似的问题是,为什么有人要存储堆(盒装)的值类型,而不是在堆栈上?

In Wikipedia there is an example for Java. But in C#, what are some cases where one would have to box a value type? Or would a better/similar question be, why would one want to store a value type on the heap (boxed) rather than on the stack?

推荐答案

在一般情况下,您通常会希望避免你的拳击值类型。

In general, you typically will want to avoid boxing your value types.

不过,也有罕见的occurances了这一点的。如果你需要为目标的1.1框架,例如,您将无法访问泛型集合。任何使用在.NET 1.1藏品需要治疗你的价值类型为一个System.Object,这会导致装箱/拆箱。

However, there are rare occurances where this is useful. If you need to target the 1.1 framework, for example, you will not have access to the generic collections. Any use of the collections in .NET 1.1 would require treating your value type as a System.Object, which causes boxing/unboxing.

有仍然是这是个案在.NET 2.0+有用。你想利用的事实,即所有类型,包括值类型,可直接视为一个对象的优势任何时候,你可能需要使用装箱/拆箱。这有时可能得心应手,因为它可以让您保存在集合中任何类型的(通过使用对象,而不是吨泛型集合),但在一般情况下,最好是避免这种情况,因为你失去的类型安全。在这里拳击经常出现的一种情况,虽然是当你使用的反思 - 许多反射调用值类型时,因为该类型无法预先知道将需要装箱/拆箱的

There are still cases for this to be useful in .NET 2.0+. Any time you want to take advantage of the fact that all types, including value types, can be treated as an object directly, you may need to use boxing/unboxing. This can be handy at times, since it allows you to save any type in a collection (by using object instead of T in a generic collection), but in general, it is better to avoid this, as you're losing type safety. The one case where boxing frequently occurs, though, is when you're using Reflection - many of the calls in reflection will require boxing/unboxing when working with value types, since the type is not known in advance.

这篇关于用例为拳击在C#中的值类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆