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>
不是。謝謝。.NET4:如何將動態綁定應用於具有返回值的匿名代理?
但我不能那樣做。我需要一個通用解決方案。 – Yegor 2010-06-20 16:43:56
@Entrase,沒有這樣的東西作爲一個通用的解決方案...如果你正在尋找普遍的答案,它是42;) – 2010-06-20 17:10:37
讓我們留在上下文中。我不是在尋找生命的意義。我只想知道爲什麼動作→動作是好的,而Func →Func 不是。請告訴我,如果你知道。 –
Yegor
2010-06-20 18:18:11