如何在C#中GC收集属性?
我想从内存中释放所有属性 为了从内存中清除这些属性,我必须断开哪个引用 我在应用程序中找不到任何具有这些属性的引用,但它们仍然没有发布如何在C#中GC收集属性?,c#,garbage-collection,attributes,C#,Garbage Collection,Attributes,我想从内存中释放所有属性 为了从内存中清除这些属性,我必须断开哪个引用 我在应用程序中找不到任何具有这些属性的引用,但它们仍然没有发布 [System.AttributeUsage(System.AttributeTargets.Property)] public class AttributeEx : System.Attribute { .... } 参考链: 为了从内存中清除这些属性,我必须断开哪个引用 只有在检查属性时才会创建属性实例,
[System.AttributeUsage(System.AttributeTargets.Property)]
public class AttributeEx : System.Attribute
{
....
}
参考链:
为了从内存中清除这些属性,我必须断开哪个引用
只有在检查属性时才会创建属性实例,而不是在创建用这些属性装饰的类型实例时。例如
var attrs = typeof(ClassWithAttribute).GetCustomAttributes();
只要attrs
是一个局部变量,该属性的寿命就会很短,很快就可以进行垃圾收集
请注意,每次调用
GetCustomAttributes
时,这些属性都会被实例化,只有在您请求时,属性才会存在于GC内存中(例如,请参见):
因此,如果你不要求它们,它们就不会被创造出来。即使您请求它们,它们也可以在不再被引用时被GC收集(因此在本例中,
bool
行之后)您还可以询问如何强制对代码进行垃圾收集。属性是程序集不可分割的一部分;GC用于在运行时动态分配的数据。是@PeterDuniho。。。理解。。那么,我怎样才能把它们从记忆中删除呢?你为什么要担心呢?使用内存分析器,找出谁拥有这些属性的引用above@PeterDuniho属性的实例在运行时动态分配,就像任何其他类型一样。
[Obsolete]
public class MyClass
{
}
// Here the ObsoleteAttribute is created
var att1 = typeof(MyClass).GetCustomAttributes(false)[0];
// Here the ObsoleteAttribute is created again
var att2 = typeof(MyClass).GetCustomAttributes(false)[0];
// false!
bool refeq = object.ReferenceEquals(att1, att2);