Tuesday, January 17, 2012

Invoking a method from its name

A few weeks ago I showed how can work a simple Server.
My client sends a pre-formatted string with the method to call and the parameters, my server processes the string and calls the correct method.
But how it can be?
I omitted that part... voluntarily. :) Let's see it!

We have this class "CM" with 1 method and 1 static method.

public class CM
{       
        //Dummy method
        public Boolean RetrieveInfo(int _par1, Guid _par2)
        {
            return _par2.ToString().Contains(_par1.ToString());
        }
        //Dummy static method
        public static string[] RetrieveInfoStatic(string _par1, bool _par2)
        {
            return new string[] { _par1, _par2.ToString() };
        }
}

Then we have our program with a test method called Example. Guess what message will be printed to Console? :)

public void Example()
{
    Object o1 = DynamicInvokeofStatic();
    Object o2 = DynamicInvokeofNonStatic(new CM());
    if (o1 is String[])
        Console.WriteLine("o1 is Ok");
    if (o2 is Boolean)
        Console.WriteLine("o2 is Ok");
}

public object DynamicInvokeofStatic()
{
    try
    {
        //Same things 
        Type desiredType = typeof(CM);
        String methodName = "RetrieveInfoStatic";
        object[] parameters = new object[] { "ALL", true };
        //I use a instance of a Reflection class to invoke my static method
        MethodInfo mInfo = desiredType.GetMethod(methodName);
        return mInfo.Invoke(this, parameters);
    }
    catch (Exception ex)
    {
        return null;
    }
}  
public object DynamicInvokeofNonStatic(CM instance)
{
    try
    {
        /* //I could load my type from a DLL
         * Assembly assembly = Assembly.LoadFrom("MyLib.dll");
         * //Create a dummy instance
         * object myObject = Activator.CreateInstance(desiredType); */

        Type desiredType = typeof(CM); //Retrieve the type from my Class        
        String methodName = "RetrieveInfo"; //Set my Method to call
        object[] parameters = new object[] { 0, Guid.NewGuid() }; //Create my parameters array

        //Invoke
        MethodInfo mInfo = desiredType.GetMethod(methodName);
        return mInfo.Invoke(instance, parameters);
    }
    catch (Exception ex) //See TargetException
    {
        return null;
    }
}

And that's all folks!

This is my (very) first post in english and I excuse myself in advance for errors. I hope this post be useful for somebody.

Goodnight.

No comments:

Post a Comment