Uredi

Deli z drugimi prek


WeakReference.Target Property

Definition

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; }
public virtual object? Target { get; set; }
member this.Target : obj with get, set
Public Overridable Property Target As Object

Property Value

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.

Exceptions

The reference to the target object is invalid. 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.

Examples

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. 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;
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

Remarks

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.

Applies to

See also