我不认为这是做你正在试图完成的任务的类型安全的方式。在更新的问题,使用例如:
private Dictionary<int, Action<IMyInterface, IMyInterface>> handler {get; set;}
public void Foo<T, U>(Action<T, U> myAction)
where T : IMyInterface
where U : IMyInterface
{
Action<IMyInterface, IMyInterface> anotherAction = (x, y) => myAction.Invoke((T)x, (U)y);
handler.Add(someInt, anotherAction);
}
假设IMyInterface的和MyImplementation定义如下:
interface IMyInterface
{
void bar();
}
class MyImplementation : IMyInterface
{
void IMyInterface.bar()
{
//Snip: Do the things
}
void nope()
{
//Snip: Do other things
}
}
class MySimplerImplementation : IMyInterface
{
void IMyInterface.bar()
{
//Snip: Do things
}
}
我们可以发现自己在以下情况:
void test()
{
//Create an action with a method that only MyImplementation implements
Action<MyImplementation, MyImplementation> forMyImplementationOnly =
(x, y) => x.nope();
//Use Foo (defined in the example code above) to 'cast' this
//action and add it to the handler dictionary
Foo<MyImplementation, Myimplementation>(forMyImplementationOnly);
//Retrieve the action from the handler dictionary
Action<IMyInterface, IMyInterface> castedAction = handler[someInt];
//Try running the action using MySimplerImplementation
castedAction(new MySimplerImplementation(), new MySimplerImplementation());
//This code will fail because MySimplerImplementation
//can not be cast to MyImplementation. It does not even
//define the nope() method that your initial Action required
}
这是这个Action泛型是逆变的原因(您可以使用较少的特定类型,但不是更具体的类型)。