我不認爲這是做你正在試圖完成的任務的類型安全的方式。在更新的問題,使用例如:
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泛型是逆變的原因(您可以使用較少的特定類型,但不是更具體的類型)。