Delegate - Method Name Expected Error
c#, delegates
Solution
Change it to this:
public decimal PerformOperation (string op, decimal x)
{
return (decimal)(functions[op].DynamicInvoke(x));
}
And it will work. However, I'd recommend something a little more strongly typed. Perhaps keep multiple dictionaries, one for each delegate type, like this:
Dictionary<string, Func<decimal, decimal>> func1;
Dictionary<string, Func<decimal, decimal, decimal>> func2;
public void AddFunction (Func<decimal, decimal> f, string name)
{
func1.Add(name, f);
}
public void AddFunction (Func<decimal, decimal, decimal> f, string name)
{
func2.Add(name, f);
}
public decimal PerformOperation (string op, decimal x)
{
return func1[op](x);
}
public decimal PerformOperation (string op, decimal x, decimal y)
{
return func2[op](x, y);
}
Problem
I'm writing a console calculator on c#. I need the following code start working: ``` Dictionary<string, Delegate> functions = new Dictionary<string, Delegate>(); private void AddMyFunction (Delegate d, string name) { if (name == null) { name = d.Method.Name; } functions.Add (name, d); } public void AddFunction (Func<decimal, decimal> f, string name) { AddMyFunction (f, name); } public void AddFunction (Func<decimal, decimal, decimal> f, string name) { AddMyFunction (f, name); } public double PerformOperation (string op, decimal x) { return functions [ op ] (x); } ``` In the function "PerformOperation" the error: "Method name expected" comes out. Please help someone.