WeakReference.Target 属性

定义

获取或设置当前 WeakReference 对象引用的对象(目标)。

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

属性值

如果当前 WeakReference 对象引用的对象已被垃圾回收,则为 null;否则引用当前 WeakReference 对象所引用的对象。

例外

对目标对象的引用无效。 设置此属性时,如果值为 null 引用或在设置操作期间终止了该对象,则可能引发此异常。

示例

以下示例尝试从具有弱引用的 对象的缓存中获取 对象。 如果对象已回收进行垃圾回收,则会生成一个新的 对象。 此示例是为 类提供的更大示例的一 WeakReference 部分。

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;
match _cache[index].Target with
| :? Data as d->
    // Object was obtained with the weak reference.
    printfn $"Regenerate object at {index}: No"
    d
| _ ->
    // If the object was reclaimed, generate a new one.
    printfn $"Regenerate object at {index}: Yes"
    let d = Data index
    _cache[index].Target <- d
    regenCount <- regenCount + 1
    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

注解

将此属性设置为目标对象后,请确保没有对对象的其他强引用;否则,将不会收集它。

适用于

另请参阅