【发布时间】:2015-05-29 21:45:42
【问题描述】:
假设我想将委托存储在这样的集合中:
public void AddDelegate<T>(Action<T> action) where T : ISomething
{
_delegates.Add(action);
}
_delegates 的类型应该是什么?
尝试IList<Action<ISomething>> _delegates;
导致上述Add 调用的错误消息Argument type 'System.Action<T>' is not assignable to parameter type 'System.Action<ISomething>'。但为什么它不起作用?编译器应该“知道”T 必须是ISomething。
如果我不想通过使用例如失去类型安全性,我有什么选择? IList<object> 或在泛型类型 T 上参数化整个类?
【问题讨论】:
-
你能把集合包装在
public class DelegateCollection<T> where T : ISomething吗? -
@DavidArno 有更好的答案