i was wondering if it is possible to pass a template into a function like this example:
Dictionary<string, Action<object>> myDict= new Dictionary<string, Action<object>>();
myDict.Add("someString",(nameOfMethod));
this method for example is a setter so it receives as a parameter (double or string or int etc...) and return void.
i suppose the following is impossible.. (i got this ERROR : Error The best overloaded method match for 'System.Collections.Generic.Dictionary>.Add(string, System.Action)' has some invalid arguments)
any ideas how to do it?
this method for example is a setter so it receives as a parameter (double or string or int etc...) and return void.
That's the problem - a method accepting a double
isn't applicable for Action<object>
, because an Action<object>
should be able to be invoked with any object
reference as the argument.
You can use a lambda expression to cast and convert though:
myDict.Add("somestring", o => MethodAcceptingDouble((double) o));
You could even write a helper method to do it, although unfortunately due to limitations of type inference you need to specify the type argument explicitly.
static class Test
{
static void Main()
{
var dictionary = new Dictionary<string, Action<object>>();
AddAction<double>(dictionary, "somestring", SampleMethod);
}
static void AddAction<T>(Dictionary<string, Action<object>> dictionary,
string name,
Action<T> action)
{
dictionary.Add(name, arg => action((T) arg));
}
static void SampleMethod(double input)
{
}
}
See more on this question at Stackoverflow