WeakReference.Target Propriedade

Definição

Obtém ou define o objeto (o destino) referenciado pelo objeto atual 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

Valor de Propriedade

null se o objeto referenciado pelo objeto atual WeakReference foi recolhido lixo; caso contrário, uma referência ao objeto referenciado pelo objeto atual WeakReference .

Exceções

A referência ao objeto alvo é inválida. Esta exceção pode ser lançada ao definir esta propriedade se o valor for uma referência nula ou se o objeto tiver sido finalizado durante a operação de set.

Exemplos

O exemplo seguinte tenta obter um objeto a partir de um cache de objetos com referências fracas. Se o objeto foi recuperado para recolha de lixo, é gerado um novo objeto. Este exemplo faz parte de um exemplo mais amplo fornecido à WeakReference turma.

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

Observações

Depois de definir esta propriedade para o objeto alvo, certifique-se de que não há outras referências fortes ao objeto; caso contrário, não será recolhido.

Aplica-se a

Ver também