简体   繁体   中英

Cannot convert type 'DelegateType' to 'System.Delegate'

I need to do something like the following but getting the above error

class PrioritizedEvent<DelegateType>
{
    private ArrayList delegates;

    public PrioritizedEvent()
    {
        this.delegates = new ArrayList();
    }

    public void AddDelegate(DelegateType d, int priority)
    {
        this.delegates.Add(new PrioritizedDelegate<DelegateType>((Delegate)d,    priority));
        this.delegates.Sort();
    }

    protected class PrioritizedDelegate<DelegateType> : IComparable
    {
        public Delegate d;
        public int priority;

        public PrioritizedDelegate(Delegate d, int priority)
        {
            this.d = d;
            this.priority = priority;
        }
    }
}

I cannot caste the DelegateType D to Delegate

Indeed, you cannot specify a : Delegate constraint - it simply cannot be done (the compiler stops you). You might find it useful to add a where DelegateType : class , just to stop usage with int etc, but you can't do this all through generics. You will need to cast via object instead:

(Delegate)(object)d

However, personally I think you should be storing DelegateType , not Delegate , ie

protected class PrioritizedDelegate : IComparable
{
    public DelegateType d;
    public int priority;

    public PrioritizedDelegate(DelegateType d, int priority)
    {
        this.d = d;
        this.priority = priority;
    }
}

Note I removed the <DelegateType> from the above: because it is nested inside a generic type ( PrioritizedEvent<DelegateType> ) it already inherits this from the parent.

For example:

class PrioritizedEvent<TDelegateType> where TDelegateType : class
{
    private readonly List<PrioritizedDelegate> delegates
        = new List<PrioritizedDelegate>();

    public void AddDelegate(TDelegateType callback, int priority)
    {
        delegates.Add(new PrioritizedDelegate(callback, priority));
        delegates.Sort((x,y) => x.Priority.CompareTo(y.Priority));
    }

    protected class PrioritizedDelegate
    {
        public TDelegateType Callback {get;private set;}
        public int Priority {get;private set;}

        public PrioritizedDelegate(TDelegateType callback, int priority)
        {
            Callback = callback;
            Priority = priority;
        }
    }
}

Your DelegateType is completely unrestricted. For all the compiler knows it could be an int or some class or a delegate.

Now normally you could use some constraints to restrict the generic type, unfortunately restricting it to a delagate is not allowed.

Marc Gravell's answer to the question why C# Generics won't allow Delegate Type Constraints gives you a workaround.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM