class MyClass
{
public event Action<string> OnAction;
public event Func<string, int> OnFunc;
}
class Program
{
static void Main(string[] args)
{
MyClass mc = new MyClass();
/// I need to handle arbitrary events.
/// But I see no way to create anonymous delegates in runtime
/// with arbitrary returns and parameters. So I choosed to
/// create multiple “signatures” with different parameter
/// number (up to 10) and different returns (either the Action or
/// Func). While Actions<> work pretty well, the Funcs<> do not.
Action<dynamic> someAction = delegate(dynamic p1) { };
Func<dynamic, dynamic> someFunc = delegate(dynamic p1) { return 42;};
// OK
mc.OnAction += someAction;
// Error: “Cannot implicitly convert type 'System.Func<dynamic,dynamic>'
// to 'System.Func<string,int>'”
mc.OnFunc += someFunc;
// It doesn't work this way as well (the same error message):
// dynamic someFunc = new Func<dynamic, dynamic>((dynamic n1) => { return 42; });
// Let's try another way
// 1:
// Cannot convert anonymous method to delegate type 'System.Func<string,int>'
// because the parameter types do not match the delegate parameter types.
// 2 (even more funny):
// Parameter 1 is declared as type 'dynamic' but should be 'string'.
mc.OnFunc += delegate(dynamic p1) { return 42; };
}
}
为什么它适用于动作而不适用于函数?换句话说,我只是想知道为什么Action<dynamic> → Action<string>
可以,而Func<dynamic,dynamic> → Func<string, int>
不能。谢谢。