.Net 4.0 Action<in T> not works for me
here is what I'm trying to do
IDictionary<Type, Action<BaseClass>> handlers = new Dictionary<Type, Action<BaseClass>>();
public void Register<T>开发者_JS百科;(Action<T> handler) where T:BaseClass
{
handlers.Add(typeof(T),handler);
}
Its not compiling
Is it possible in another way?
Covariant parameters work in the other direction.
Action<in T>
allows you to write
Action<Animal> baseProcessor = ...;
Action<Cat> catProcessor = baseProcessor;
Since all Cat
s are also Animals
, this is legal.
Had your code been possible, what would happen if I write
Action<Cat> catProcessor = ...;
Action<Animal> baseProcessor = catProcessor;
baseProcessor(new Dog());
We just passed a Dog
to a function that takes a Cat
.
IDictionary<Type, Action<BaseClass>> handlers = new Dictionary<Type, Action<BaseClass>>();
public void Register<T>(Action<T> handler) where T:BaseClass
{
Action<BaseClass> action = x=>handler((T)x);
handlers.Add(typeof(T),action);
}
精彩评论