2013-06-13 55 views
1

我需要做類似下面的,但得到上述錯誤不能鍵入「DelegateType」轉換爲「System.Delegate」

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要委派

回答

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

DelegateType是完全不受限制。對於所有的編譯器知道它可能是一個int或某個類或委託。

現在通常情況下,您可以使用一些約束來限制泛型類型,但不允許將其限制爲delagate。

Marc Gravell's回答爲什麼C# Generics won't allow Delegate Type Constraints爲您提供解決方法。

相關問題