无法将类型'DelegateType'转换为'System.Delegate'

时间:2013-06-13 08:06:05

标签: c# events

我需要执行以下操作,但会收到上述错误

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;
        }
    }
}

我无法将DelegateType D委托给代表

2 个答案:

答案 0 :(得分:1)

实际上,您无法指定: Delegate约束 - 它根本无法完成(编译器会阻止您)。您可能会发现添加where DelegateType : class非常有用,只是为了停止使用int等,但您无法通过泛型完成此操作。您需要通过object投射:

(Delegate)(object)d

但是,我个人认为你应该存储DelegateType,而不是Delegate,即

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

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

注意我从上面删除了<DelegateType>:因为它嵌套在泛型类型(PrioritizedEvent<DelegateType>)中,它已经从父类继承了它。

例如:

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;
        }
    }
}

答案 1 :(得分:0)

您的DelegateType完全不受限制。对于所有编译器都知道它可以是int或某个类或委托。

现在通常你可以使用一些约束来限制泛型类型,不幸的是,不允许将它限制为delagate。

Marc Gravell's回答了C# Generics won't allow Delegate Type Constraints为什么会为您提供解决方法的问题。