Reputation: 45
I am trying to implement small console-like commands to ASP .Net Core App. I have a class which stores names and method that should be run:
public class ActionCenter
{
public string ActionName { get; set; }
public Action ActionStart { get; set; }
}
And I have a list List<ActionCenter> Actions
where I store all the commands and methods associated with them. To run method I can do Actions[0].ActionStart.Invoke
, but I do not have return of the method. I tried Task<object>
but cannot convert System.Action
to System.Func<object>
. Is there a way to have return from methods designed this way if not what is the right way?
Upvotes: 0
Views: 3213
Reputation: 53958
As it is stated at the documentation an Action
:
Encapsulates a method that has no parameters and does not return a value.
public delegate void Action()
That being said you cannot achieve that you want with an action. On the other hand, a Func<TResult>
:
Encapsulates a method that has no parameters and returns a value of the type specified by the TResult parameter.
So in your case you need a Func
rather than an Action
. If we say that you expect your method to return always an int
, you should have a Func<int>
etc. Furthremore, Funcs as Actions can get a list of parameters, if your method is going to have any. So for instance, if your have a method that takes two parameters of type int and returns another int, the signarture of your Func, it would be Func<int,int,int>
.
Upvotes: 1