一个类如果没有定义为static但里面的属性是static的
该属性会被回收吗?
如果类是定义为static的呢?
例如:public class Test1
{
    public static string Name;
}
public static class Test2
{
    public static string Name;
}Test1中的Name什么时候会被回收?Test2中的Name什么时候会被回收?

解决方案 »

  1.   

    static的本意是静态的,即一直存在于内存当中,直到你修改了它的值或者程序关闭时会改变或销毁。
      

  2.   

    我的程序的有个类是Test1类型的,不是static类
    但程序运行一段时间后,可能是几天
    中间会出现Name为空的情况
    造成取值失败
    难道不是被回收了吗
      

  3.   

    两个例子中的Name属性本身占的32个bit是永远不会回收的
    按常理推断,它指向的对象一旦你设置Name=null并且没有其他引用时就可以被回收但string又是个特殊的类,有可能有什么缓存之类的东西就不晓得了
      

  4.   

    不会回收的。参见《CLR via C#》一书的说明:
    A static field keeps whatever object it refers to forever or until the AppDomain 
    that the types are loaded into is unloaded. A common way to leak memory is to have a 
    static field refer to a collection object and then to keep adding items to the collection object. The static field keeps the collection object alive and the collection object keeps all its 
    items alive. For this reason, it is best to avoid static fields whenever possible.
      

  5.   

    定义为静态的任何东西,永远不可能被回收,除非你自己将其设置为null,将引用去掉了,才可能被GC回收,如果遇到奇怪的现象,请检查代码其它地方。
      

  6.   

    (无论是否静态类的)静态成员,只有到AppDomain.UnLoad时才会回收。静态类只允许存在静态成员
      

  7.   

    不会回收,知道该程序域卸载或应用程序关闭。如果是引用类型变量可以显示的设置为null,该对象才会被标记为垃圾,才会被回收