WeakReference.Target 属性
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
获取或设置当前 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
属性值
null 如果当前对象引用 WeakReference 的对象已被垃圾回收,则为对当前对象的引用;否则为对当前 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
注解
将此属性设置为目标对象后,请确保没有对对象的其他强引用;否则,不会收集它。