共用方式為


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

備註

將此屬性設定為目標物件之後,請確定物件沒有其他強式參考;否則,將不會收集它。

適用於

另請參閱