我感觉常量是不能修改的,是不需要放到堆空间中去的。只要放到运行内存空间(像代码一样)即可。 但是下面的文章说,还是放到heap中的。还有因为const默认就是static,因此不需要很类实例一起创建,和销毁,而是第一次访问时创建,然后,一直存在于heap中。Static data and constants defined in a C# program are stored on the heap. Since they exist for the lifetime of the application, they do not need to be garbage collected and are therefore stored in a loader heap, rather than the normal Garbage Collected heap. Specifically, static data is stored on the high-frequency heap–one of the loader heaps that exists for each AppDomain来自: #200 – Static Data and Constants Are Stored on the Heap http://csharp.2000things.com/2011/01/03/200-static-data-and-constants-are-stored-on-the-heap/
请看下面:
{//下面就实验一下:
{
string a;
MessageBox.Show(a);//ok <a>
}
MessageBox.Show(a);//出错:a 没有定义! ,这时内存释放了//如果删了<a>语句,这里同样出错,所以这内存占用只与作用域有关,与调用没有调用无关
}
上面的代码,你试试就知的!
{
string a;
MessageBox.Show(a);//ok <a>
}
MessageBox.Show(a);//出错:a 没有定义! ,这时内存释放了//如果删了 <a> 语句,这里同样出错,所以这内存占用只与作用域有关,与调用没有调用无关
}
不明白的是:假如我就再某个类定义了一个常量字符串string str="string";再也没有其他地方用到"string"这个字符串了,那这个字符串是不是在程序结束前一直在内存呢?假如不是我所想的这样,又是怎样,解释下啊。。
String是只读,不可变的串,无法修改这是它的最基本也是最常用的特征。
NET内部对于字符串做了相当多的努力,尤其是这个不可变的特性,防止打乱,修改,变长变短等等。
你说的会长期在内存中长期存在这是不准确的,虽然CLR确实有字符串留用就是我们常说的“拘留池”,你可以采用String的Intern方法留用字符串,但这跟CLR版本以及程序代码有关,这样是在一定程度让再次用或者常用的字符串只存储一个以便复用,但这不代表内存一直存储,当然这可能会是用性能换取效率。
对于字符串照样满足CLR的GC机制,如果CLR发现字符串不可达或者不再引用时照样会回收。
但是下面的文章说,还是放到heap中的。还有因为const默认就是static,因此不需要很类实例一起创建,和销毁,而是第一次访问时创建,然后,一直存在于heap中。Static data and constants defined in a C# program are stored on the heap. Since they exist for the lifetime of the application, they do not need to be garbage collected and are therefore stored in a loader heap, rather than the normal Garbage Collected heap. Specifically, static data is stored on the high-frequency heap–one of the loader heaps that exists for each AppDomain来自:
#200 – Static Data and Constants Are Stored on the Heap
http://csharp.2000things.com/2011/01/03/200-static-data-and-constants-are-stored-on-the-heap/
如果,static ,const 是不占用内存的,那么它的数据放在哪儿?
不放在内存中?那放在硬盘中? (好像电脑只有这两个东东可以放数据。),如不放在内存中,那么每次引用 static ,const 量,都去硬盘中读,那会损机的。
我的个人理解是:
放在内存中,只是设定它为只读而已。
不知,以上是不是正解的。
Replay:这两个都是基础的知识,这是LZ在问问题,我们不该喧宾夺主。