WeakReference.Target WeakReference.Target WeakReference.Target WeakReference.Target Property

定义

获取或设置当前 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

属性值

如果当前 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. 此示例摘自一个更大的示例为提供WeakReference类。This 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.

适用于

另请参阅