简体   繁体   English

C#中索引器的内存分配

[英]Memory allocation for an indexer in c#

I am using Indexer in C# but I want to know at what time memory will be allocated for indexer because indexer contains array of object. 我在C#中使用索引器,但是我想知道什么时候将为索引器分配内存,因为索引器包含对象数组。 Here is a demo code for indexer. 这是索引器的演示代码。

   class person{
    private object[] _demo = new object[ 2 ];
    public object this[int i]
    {
        get { return _demo[ i ]; }
        set { _demo[ i ] = value; }
    } }

Now My question is at what time memory will be allocated for indexer because indexer can contains all types of datatype values. 现在我的问题是什么时候将为索引器分配内存,因为索引器可以包含所有类型的数据类型值。

There are three completely separate pieces here: 这里有三个完全独立的部分:

  1. The indexer. 索引器。 It uses no memory . 不占用内存 It's just methods to tell the program where to look for other things that do use memory. 这只是告诉程序在哪里寻找其他确实使用内存的方法的方法。
  2. The object[2] array. object[2]数组。 The array is itself an object that uses memory. 数组本身就是使用内存的对象。 However, this object only stores references , and so it will always be the same size, no matter what you put in it. 但是,此对象仅存储引用 ,因此无论您放入什么对象,它都将始终具有相同的大小。
  3. Any objects you put in the array use their own memory. 您放入数组中的任何对象都使用其自己的内存。 Small objects use a little memory, but big objects can use a lot. 小对象占用一点内存,但是大对象可能占用很多内存。 However, because the array only stores references, the memory for this is only the original memory used for the object itself. 但是,由于数组仅存储引用,因此该内存仅是对象本身使用的原始内存。

All that out of the way, object arrays are rarely a good design choice, both for the "object" and the "array" part. 不管怎样,对于“对象”和“数组”部分,对象数组很少是一个好的设计选择。

The indexer doesn't contain any memory. 索引器不包含任何内存。 It's just a pair of methods, one for getting and one for setting. 这只是一对方法,一个用于获取,一个用于设置。 The array that you use internally to implement the indexer does take up memory, and it's allocated when an instance of the class is allocated via new . 内部用于实现索引器的数组占用内存,并且当通过new分配类的实例时会分配该数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM