Both Action and Func <T> without explicit casting

I have a class that needs to receive methods for calling them, as well as for other executions. These methods should be used many times for different users, so the simpler the better.

To deal with this, I have two methods:

void Receive(Action func) { // Do some things. func(); } T Receive<T>(Func<T> func) { // Do some things. return func(); } 

(Actually, I have 34 methods to be able to get any of the specific Action or Func.)

Then I want to be able to pass any method as a parameter to the Receive function in order to be able to do something like this:

  void Test() { Receive(A); Receive(B); } void A() { } int B() { return 0; } 

Just like this, it gives me one error in Receive (B):

 The call is ambiguous between the following methods or properties: 'Class1.Receive(System.Action)' and 'Class1.Receive<int>(System.Func<int>)' 

Well, the signature is the same (although errors do not appear if I do not use the methods).

If I remove the Receive (Action) method, I get the following error in Receive (A):

 The type arguments for method 'Class1.Receive<T>(System.Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. 

But my type is not valid in this case, and it is forbidden to use it as a general parameter.

So, is there a way to get a receive method without using any explicit Action or Func actions?

+7
source share
2 answers

No, you cannot do this - void not a valid return type for Func<T> . The best you can do is wrap it in a Func<object> :

 Receive(() => { A(); return null; }); 
+4
source

Try explicitly specifying a generic parameter:

 Receive<int>(B); 
+3
source

All Articles