WeakReference.Target 属性

定义

获取或设置当前 WeakReference 对象引用的对象(目标)。Gets or sets the object (the target) referenced by the current WeakReference object.

public:
 virtual property System::Object ^ Target { System::Object ^ get(); void set(System::Object ^ value); };
public virtual object Target { get; set; }
member this.Target : obj with get, set
Public Overridable Property Target As Object

属性值

Object

如果当前 WeakReference 对象引用的对象已被垃圾回收,则为 null;否则引用当前 WeakReference 对象所引用的对象。null if the object referenced by the current WeakReference object has been garbage collected; otherwise, a reference to the object referenced by the current WeakReference object.

例外

对目标对象的引用无效。The reference to the target object is invalid. 设置此属性时,如果值为 null 引用或在设置操作期间终止了该对象,则可能引发此异常。This exception can be thrown while setting this property if the value is a null reference or if the object has been finalized during the set operation.

示例

下面的示例尝试从具有弱引用的对象的缓存中获取一个对象。The following example tries to obtain an object from a cache of objects with weak references. 如果对象被回收以进行垃圾回收,则会生成一个新的对象。If the object was reclaimed for garbage collection, a new object is generated. 此示例是为类提供的更大示例的一部分 WeakReferenceThis example is part of a larger example provided for the WeakReference class.

Data d = _cache[index].Target as Data;
if (d == null) {
    // If the object was reclaimed, generate a new one.
    Console.WriteLine("Regenerate object at {0}: Yes", index);
    d = new Data(index);
    _cache[index].Target = d;
    regenCount++;
}
else {
    // Object was obtained with the weak reference.
    Console.WriteLine("Regenerate object at {0}: No", index);
}

return d;
 Dim d As Data = TryCast(_cache(index).Target, Data)
 ' If the object was reclaimed, generate a new one.
 If d Is Nothing Then 
     Console.WriteLine("Regenerate object at {0}: Yes", index)
     d = New Data(index)
     _cache(index).Target = d
     regenCount += 1
Else 
     ' Object was obtained with the weak reference.
     Console.WriteLine("Regenerate object at {0}: No", index.ToString())
 End If 
 Return d

注解

将此属性设置为目标对象后,请确保不存在对该对象的任何其他强引用;否则,将不会收集它。After setting this property to the target object, make sure that there are no other strong references to the object; otherwise, it will not be collected.

适用于

另请参阅