如何C#泛型集合的影响与原语 [英] How does C# generics affect collections with primitives

查看:138
本文介绍了如何C#泛型集合的影响与原语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,C#/。NET泛型支持某种程度的具体化。所以,如果我有以下的code:

As I understand it, C#/.Net generics support some degree of reification. So, if I have the following code:

List<int> list = new List<int>();
list.Add(1);

请问价值1被autoboxed或将列表对象有效地处理原始整数?

Will the value 1 be autoboxed or will the 'list' object handle primitive ints efficiently?

推荐答案

没有,它不会被装箱。在执行时,支持数组为名单,其中,INT&GT; 将真正成为一个 INT [] 。请注意,这不只是与真正的原始类型的情况下 - 名单,其中,T&GT; 不会的的任意的值类型(假设框中的值是被宣布为名单,其中,的Guid&GT; 等,而不是名单,其中,对象&gt;

No, it won't be boxed. At execution time, the backing array for the List<int> will genuinely be an int[]. Note that this isn't just the case with genuine primitive types - List<T> won't box values of any value type (assuming it's been declared as List<Guid> etc rather than List<object>).

基本上,在.NET泛型保持更多他们的信息比他们在Java中 - 在CLR本身理解泛型和处理它们适当的,而不是在Java中,其中JVM是pretty的很多无知的人。

Basically, generics in .NET keep a lot more of their information than they do in Java - the CLR natively understands generics and deals with them appropriately, rather than in Java where the JVM is pretty much ignorant of them.

例如,如果你写的:

object list = new List<string>();
Type type = list.GetType();

然后键入将等于的typeof(名单&LT;字符串&GT;) - 它是那么不同(比如)名单,其中,的Guid&GT;

Then type will be equal to typeof(List<string>) - which is then different to (say) List<Guid> etc.

这篇关于如何C#泛型集合的影响与原语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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