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; };
}
}
조치에 대해 작동하고 기능에 대해 작동하지 않는 이유는 무엇입니까? 다른 말로하면 이 괜찮 으면 Func<dynamic,dynamic> → Func<string, int>
이 아닌 이유를 알고 싶습니다. 감사..NET4 : 반환과 함께 익명의 대리자에 동적 바인딩을 적용하는 방법?
하지만 그럴 수 없습니다. 나는 보편적 인 해결책이 필요하다. – Yegor
@Entrase, 보편적 인 해결책과 같은 것은 없습니다 ... 보편적 인 답을 찾으려면 42입니다.) –
상황에 처하게하십시오. 나는 삶의 의미를 찾고 있지 않습니다. 나는 단지 이유를 알고 싶습니다. → Func → Func 은 동작하지 않습니다. → 작업은 정상입니다. 알고 계시다면 알려주세요. –
Yegor