在C#中,是一个List&LT值;结构>盒装? [英] In C#, are the values in a List<struct> boxed?

查看:123
本文介绍了在C#中,是一个List&LT值;结构>盒装?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我声明包含一个结构类型的值的泛型列表:

Suppose I declare a generic List containing values of a struct type:

struct MyStruct {
    public MyStruct(int val1, decimal val2) : this() {
        Val1 = val1;
        Val2 = val2;
    }
    public int Val1 {get; private set;}
    public decimal Val2 {get; private set;}
}

List<MyStruct> list;



请问名单<>存储每个单独的值作为套装结构,在堆上单独分配?或者比它更聪明?

Does the List<> store each individual value as a boxed struct, allocated individually on the heap? Or is it smarter than that?

推荐答案

有没有拳击。

不,不会有拳击,这是泛型的主要设计目标之一。

"No, there will be no boxing. That was one of the main design goals of Generics."

HTTP://social.msdn。 microsoft.com/Forums/en-US/csharplanguage/thread/359cf58a-f53d-478e-bc31-1507e77c9454/

该值类型类专门也就是说,一个列表元素<;如果一个值类型用于T类型,编译器生成名单,LT的实现; T>。 code>列表< T> 对象没有被装箱可以使用元素之前,并创造了约500列表元素后,保存在记忆不是拳击列表元素比内存大用于生成类实现。

"If a value type is used for type T, the compiler generates an implementation of the List<T> class specifically for that value type. That means a list element of a List<T> object does not have to be boxed before the element can be used, and after about 500 list elements are created the memory saved not boxing list elements is greater than the memory used to generate the class implementation."

http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx

这篇关于在C#中,是一个List&LT值;结构&GT;盒装?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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