How to recover the value of Func, Action of a Dictionary. C #

0

I'm doing a dictionary, in which the key is a String and the value could be an Action or Func.

Dictionary < string, Action<string> > DicAction;
Dictionary < string, Func<string> > DicFunc;

Instance dictionaries;

DicAction =  new Dictionary < string , Action<string> ();
DicFunc   =  new Dictionary < string , Func<string>();

Insert the parameters into the dictionary.

DicAction.Add("RecuperaListaAction", data => { 

 return (data=="RESULT") ? List<Item> : null;

});

DicFunc.Add("RecuperaListaFunc", data => { 

 return (data=="RESULT") ? List<Item> : null;

});

My question is how do I collect the returned value

var resultListAction = DicAction["RecuperaListaAction"]("RESULT");
var resultListFunc   = DicFunc["RecuperaListaFunc"]("RESULT");

Since I am not able to recover the data.

    
asked by dGame 01.09.2017 в 16:20
source

1 answer

1

First by part:

1

 Dictionary <string, Action<string>> DicAction;

The System.Action have no return type, you can only specify parameters but not return types so this is invalid:

DicAction.Add("RecuperaListaAction", data => { 

 return (data=="RESULT") ? List<Item> : null; // no puedes retornan en un delegado tipo System.Action
});

In your case the Action<String> means that you expect a delegate who has a parameter of type String :

The valid way to do it would be:

 DicAction.Add("RecuperaListaAction", (parametroString) => {
                // no puedes hacer retorn...
});

2

Dictionary <string,Func<string>> DicFunc;

Unlike action, delegates System.Func if they return and the return type would be the last defined generic parameter.

In your case Func<String> means that you expect a delegate to return System.String without parameters but in your code you define that you expect a parameter and return so it is invalid:

DicFunc.Add("RecuperaListaFunc", data => { 
 return (data=="RESULT") ? List<Item> : null;
});

In order for it to work, you have to specify another generic parameter to accept a parameter string and return string that would be:

   Dictionary < string, Func<string, string> > DicFunc;

So now if what you expect is valid.

Then the final code would be:

  Dictionary<string, Action<string>> DicAction;
Dictionary<string, Func<string, string>> DicFunc;

DicAction = new Dictionary<string, Action<string>> ();
DicFunc = new Dictionary<string, Func<string,string>>();

DicAction.Add("RecuperaListaAction", (str) => {

});

DicFunc.Add("RecuperaListaFunc", (str) => {

    return (str == "RESULT") ? List<T> : null;
});

And it runs as follows:

DicAction["key"]("datos");// los actions no returnan 
String resultado = DicFunc["key"]("parametro"); // func si retornan por lo que podemos almacenar el valor de retorno
    
answered by 01.09.2017 / 16:31
source