WeakReference.Target Propriedade
Definição
Obtém ou define o objeto (o destino) referenciado pelo objeto WeakReference atual.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
Valor da propriedade
null se o objeto referenciado pelo objeto WeakReference atual passou pela coleta de lixo; caso contrário, uma referência ao objeto referenciado pelo objeto WeakReference atual.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.
Exceções
A referência ao objeto de destino é inválida.The reference to the target object is invalid. Essa exceção pode ser gerada ao configurar essa propriedade se o valor for uma referência nula ou se o objeto tiver sido finalizado durante a operação de conjuntos.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.
Exemplos
O exemplo a seguir tenta obter um objeto de um cache de objetos com referências fracas.The following example tries to obtain an object from a cache of objects with weak references. Se o objeto tiver sido recuperado para coleta de lixo, um novo objeto será gerado.If the object was reclaimed for garbage collection, a new object is generated. Este exemplo faz parte de um exemplo maior fornecido para a WeakReference classe.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
Comentários
Depois de definir essa propriedade para o objeto de destino, verifique se não há outras referências fortes ao objeto; caso contrário, ele não será coletado.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.