Reputation: 1
Given the two following method definitions:
public int SumClass(int a, int b)
{
return a + b;
}
public int MultClass(int a, int b)
{
return a * b;
}
I would like to be able to call either of the methods using the name of the method as a string
public int Process(string className, int a, int b)
{
// className="SumClass" or className="MultClass"
return className(a,b);
}
Upvotes: 0
Views: 76
Reputation: 1647
I'd prefer the approaches mentioned above but in case you are specifically looking for reflection based approach here it is.
Be warned that you will not get any type safety and no way to know if the method you are trying to call actually exists on the object and it may fail at runtime.
public class Test
{
public int Process(string className, int a, int b)
{
// className="SumClass" or className="MultClass"
return (int)(typeof (Test).GetMethod(className, BindingFlags.Instance | BindingFlags.Public)
.Invoke(this, BindingFlags.InvokeMethod, null, new Object[] {a, b}, CultureInfo.CurrentCulture));
}
public int SumClass(int a, int b)
{
return a + b;
}
public int MultClass(int a, int b)
{
return a * b;
}
}
Upvotes: 1
Reputation: 18583
Use a dictionary of string to delegate either containing the implementation or proxying to the implementation:
//Setup
static Dictionary<string,Func<int,int,int>>() lookups = new Dictionary<string,Func<int,int,int>>();
static classname() { //static constructor
lookups.Add("SumClass", (a,b) => {
return a + b;
});
lookups.Add("MultClass", (a,b) => {
return a * b;
});
}
//Use
public int Process(string className, int a, int b)
{
// className="SumClass" or className="MultClass"
return lookup[className](a,b); //not exactly the same as your request, but close and still a string.
}
Upvotes: 1
Reputation: 2522
Define an interface like IOperation:
public interface IOperation
{
int DoMe(int a, int b);
}
Now you can handle this in one place and create any number of implementations. e.g:
public class Addition : IOperation
{
public int DoMe(int a, int b)
{
return a + b;
}
}
Then just Process(IOperation operation, int a, int b).
Upvotes: 0
Reputation: 460158
I could show you a reflection approach which would do what you want. But i won't because there is almost always a better approach. Why do you want that? Because you have different methods for addition and multiplication. One better way is to to use an enum
:
public enum ProcessType {
Multiplication,
Addition,
Division,
Subtraction
}
public int Process(ProcessType processType, int a, int b)
{
switch (processType)
{
case ProcessType.Addition:
return SumClass(a, b);
case ProcessType.Multiplication:
return MultClass(a, b);
// ...
}
}
So if you want to sum 2 + 3:
int result = Process(ProcessType.Addition, 2, 3);
Upvotes: 2