Унаследованный WeakReference, генерирующий исключение ReflectionTypeLoadException в Silverlight - PullRequest
5 голосов
/ 13 июля 2010

Я пытаюсь использовать типизированный WeakReference в своем приложении Silverlight. Я следую рецепту на этом сайте: http://ondevelopment.blogspot.com/2008/01/generic-weak-reference.html только с использованием System.WeakReference и опускаю материал, который ссылается на сериализацию.

При попытке запуска выдается исключение ReflectionTypeLoadException с сообщением:

"{System.TypeLoadException: правила безопасности наследования, нарушенные при переопределении члена: 'Coatue.Silverlight.Shared.Cache.WeakReference`1..ctor ()'. Доступность безопасности переопределяющего метода должна соответствовать доступной безопасности метода будучи переопределенным.} "

Есть предложения?

РЕДАКТИРОВАТЬ: Вот код, который я использую:

using System;

namespace Frank
{
    public class WeakReference<T>
        : WeakReference where T : class
    {
        public WeakReference(T target)
            : base(target) { }

        public WeakReference(T target, bool trackResurrection)
            : base(target, trackResurrection) { }

        protected WeakReference() : base() { }

        public new T Target
        {
            get
            {
                return (T)base.Target;
            }
            set
            {
                base.Target = value;
            }
        }
    }
}

Ответы [ 3 ]

5 голосов
/ 13 июля 2010

Как упоминал Томас, вы не можете наследовать от слабой ссылки в серебряном свете, но вы можете обернуть ее:

using System;

namespace Frank
{
    public class WeakReference<T> where T : class
    {
        private readonly WeakReference inner;

        public WeakReference(T target)
            : this(target, false)
        { }

        public WeakReference(T target, bool trackResurrection)
        {
            if(target == null) throw new ArgumentNullException("target");
            this.inner = new WeakReference(target, trackResurrection);
        }

        public T Target
        {
            get
            {
                return (T)this.inner.Target;
            }
            set
            {
                this.inner.Target = value;
            }
        }

        public bool IsAlive {
            get {
                 return this.inner.IsAlive;
            }
        }
    }
}
3 голосов
/ 13 июля 2010

Существует требование наследования для класса WeakReference, и среда выполнения Silverlight не имеет необходимых разрешений. Таким образом, вы не можете наследовать WeakReference в Silverlight ...

[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
0 голосов
/ 21 февраля 2011
using System;

namespace Harmony.Ria
{
    public class WeakReference<T>
        where T : class
    {
        private WeakReference inner;

        /// <summary>
        /// Initializes a new instance of the System.WeakReference class, referencing 
        /// the specified object.
        /// </summary>
        /// <param name="target">The object to track or null.</param>
        public WeakReference(T target)
            : this(target, false)
        { }

        /// <summary>
        /// Initializes a new instance of the System.WeakReference 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)
        {
            if (target == null) throw new ArgumentNullException("target");
            this.inner = new WeakReference((object)target, trackResurrection);
        }

        /// <summary>
        /// Gets or sets the object (the target) referenced by the current 
        /// System.WeakReference object.
        /// </summary>
        public T Target { get { return (T)this.inner.Target; } set { this.inner.Target = value; } }

        /// <summary>
        /// Gets an indication whether the object referenced by the current 
        /// System.WeakReference object has been garbage collected.
        /// </summary>
        public bool IsAlive { get { return this.inner.IsAlive; } }

        /// <summary>  
        /// Casts an object of the type T to a weak reference  
        /// of T.  
        /// </summary>  
        public static implicit operator WeakReference<T>(T target)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }
            return new WeakReference<T>(target);
        }

        /// <summary>  
        /// Casts a weak reference to an object of the type the  
        /// reference represents.  
        /// </summary>  
        public static implicit operator T(WeakReference<T> reference)
        {
            if (reference != null)
            {
                return reference.Target;
            }
            else
            {
                return null;
            }
        }
    }
}
...