Search

Custom Search

Friday, April 18, 2008

Calling A Method By Name

Sometimes we are developing a system that is very much dependent in the database. I call this style as Data Driven Development where everything depends on the database. Even for Buttons that should be available on screen. I have develop a Touch Screen System before using Delphi where Buttons are created Dynamically depending on the set of data returned by the database. This means that each buttons calls its method by function name. To achieve this we set a centralize Event Handler for all Buttons Created Dynamically and then call the routine by Name. That is easy in Delphi for you can call routines of a protected method by Name.
When I shifted to C# I wonder how will I achieve that same functionality. Atlast with some few trials and hard work, I have created a class to handle this. The code is as follows:

public delegate void methodDelegate();
public class FunctionByName
{
private ArrayList
ListOfMethodAddress = new
ArrayList();
private ArrayList
ListOfMethodName = new ArrayList();
public void
AddMethod(methodDelegate
MethodAddress)
{
ListOfMethodName.Add(MethodAddress.Method.Name);
ListOfMethodAddress.Add(MethodAddress);
}

public void ExecMethod(string
MethodName)
{
if
(ListOfMethodName.Contains(MethodName))
{
int MethodIndex =
ListOfMethodName.IndexOf(MethodName);
methodDelegate toExec = new
methodDelegate((methodDelegate)ListOfMethodAddress[MethodIndex]);
toExec();

}
}

}


The difference is that you should add all delegates that you want to be called by name using AddMethod, Then to execute it you call ExecMethod("MyFunction"), Here you are calling MyFunction Method but it should be added initially before you can call it.

Updated: Below is a new version of my CallFunctionByName Class it. It uses Dictionary rather than ArrayList:


public delegate void methodDelegate();
public class
FunctionByName
{
private Dictionary
ListOfMethod = new Dictionary();
public void
AddMethod(methodDelegate
MethodAddress)
{
ListOfMethod.Add(MethodAddress.Method.Name,
MethodAddress);
}
public void ExecMethod(string MethodName)
{
if
(ListOfMethod.ContainsKey(MethodName))
{
methodDelegate toExec =
(ListOfMethod[MethodName]);
toExec();
}
else
{
throw new
Exception("Not yet Implemented");
}
}
}

No comments:

Post a Comment

Adsense Banner