65.9K
CodeProject 正在变化。 阅读更多。
Home

通用弱引用

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.67/5 (3投票s)

2007年12月21日

CPOL
viewsIcon

31418

downloadIcon

96

WeakReference 类的通用实现。

引言

在 .NET Framework 中,System.WeakReference 类没有泛型实现。这意味着开发者必须进行运行时类型转换,这容易出错且重复。我做了这个简单的实现来解决这个问题。当然,它无法解决装箱引入的开销,因为它仍然存储在基类中的 object 变量中。希望未来版本的框架会包含一个真正的泛型 WeakReference

Using the Code

只需复制下面的代码片段并将其粘贴到您的项目中即可使用。

    /// <summary>
    /// Represents a weak reference, which references an object while still allowing
    /// that object to be reclaimed by garbage collection.
    /// </summary>
    /// <typeparam name="T">The type of the object that is referenced.</typeparam>
    [Serializable]
    public class WeakReference<T>
        : WeakReference where T : class
    {
        /// <summary>
        /// Initializes a new instance of the WeakReference{T} class, referencing
        /// the specified object.
        /// </summary>
        /// <param name="target">The object to reference.</param>
        public WeakReference(T target)
            : base(target)
        { }
        /// <summary>
        /// Initializes a new instance of the WeakReference{T} class, referencing
        /// the specified object and using the specified resurrection tracking.
        /// </summary>
        /// <param name="target">An object to track.</param>
        /// <param name="trackResurrection">Indicates when to stop tracking the object. 
        /// If true, the object is tracked
        /// after finalization; if false, the object is only tracked 
        /// until finalization.</param>
        public WeakReference(T target, bool trackResurrection)
            : base(target, trackResurrection)
        { }
        protected WeakReference(SerializationInfo info, StreamingContext context)
            : base(info, context)
        { }
        /// <summary>
        /// Gets or sets the object (the target) referenced by the 
        /// current WeakReference{T} object.
        /// </summary>
        public new T Target
        {
            get
            {
                return (T)base.Target;
            }
           set
            {
                base.Target = value;
            }
        }
    }        

历史

  • 2007年12月21日:初始发布
© . All rights reserved.