I’m trying to cast Func<>'s into a delegate. Can anyone help please?
private delegate WWW QueryAction(params string[] data);
private Dictionary<string, QueryAction> querys;
private void Awake()
{
//Func<int> myDelegate = () => 1 + 2 + a + b;
WWW ss;
querys = new Dictionary<string, QueryAction>();
querys.Add(RequestType.Login.ToString(), (QueryAction)Func<string, string, WWW> ss = (a, b) => a ); // <-- This doesn't work. I want to choose the number of parameters for each <key, value> pair to make dynamic queries
querys.Add(RequestType.ContactInfo.ToString(), (((d) => new WWW(""))));
}
I’m doing this because Func<>'s can’t have params, but delegates can. So I want to cast static argument Func<>'s into the delegate.
Not quite sure I’m getting what you’re trying to do. You can’t cast a Func to a queryAction because none of the Func delegates have param arguments. But what do you need the Func’s for in the first place?
First off… Func<> is a delegate (well technically Func<> isn’t, because there needs to be a result type generic… Func is a delegate, Func<> doesn’t exist):
Next, there are generic versions of the Func<> delegate that takes different numbers of parameters:
2 param
3 param
4 param
etc
Note, each of these are DISTINCT types. They all happen to have similar names. Func is not interachangeable with Func<T1, TResult>… they could just as easily be called ‘FuncWithNoParams’ and ‘FuncWithOneParam<T1, TResult>’.
Your delegate on the other hand is of type ‘QueryAction’
To say “cast Func<> into a delegate” is like saying “cast MonoBehaviour into a class”. They are already that.
What you mean is you want to cast a delegate from one type to the other. Like casting MonoBehaviour to Component.
Problem is… you can’t.
In your situation it’d be like casting a MonoBehaviour to a Rect… they’re 2 completely different types. One takes in an array of strings and outputs a WWW, the other takes in 2 strings and outputs a WWW.
Thing is… you’re also using anonymous/lambda functions to do this. These are anonymous. Just remove the whole ‘Func<string,string,WWW>’ bit and let it be a QueryAction, you’ll just have to shape the input parameters appropriately (accepting a params array, rather than 2 independent strings).
So really, all you need is to do this:
private delegate WWW QueryAction(string[] data);
...
querys = new Dictionary<string, QueryAction>();
querys.Add("test", (data) => {
return new WWW(data[0]); //I don't know what you want here
});