Dynamic casting of string to other .net objects like XMLElement, Color

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Sri13
    New Member
    • Sep 2010
    • 11

    Dynamic casting of string to other .net objects like XMLElement, Color

    Hi

    I am trying to read the parameters of a method dynamically and then call that method with the passed parameter values (string type). I am able to write the code that reads the parameter of simple .net types like - string, int, float, double etc. I read them and convert to required type using ChangeType method. But I am not able to make the code work for other types like - XMLElement, Color, etc.

    Here is my generic code that reads parameters and the datatype dynamically to add them to the argument list object.

    Code:
    ParameterInfo[] parameters = type.GetMethod(methodName).GetParameters();
    List<object> argumentList = new List<object>();
    foreach (var parameter in parameters)
    {
        //Check for custom type
        if (IsCustomType(parameter.ParameterType))
        {                   
            //TypeDescriptor.GetProperties(item)["CheckBackColor"].SetValue(item, Color.FromName("Red"));
            
            //Build parameter list
            object item = BuildParameterList(parameter.ParameterType);
    
            argumentList.Add(item);
        }
        else
        {   
            argumentList.Add(Convert.ChangeType(property[parameter.Name], parameter.ParameterType));
        }
    }
    The problem is in the last line where I am trying to change type for the value based on the parameter type. If my parameter is XMLElement type then it throws error: Invalid cast from 'System.String' to 'System.Xml.Xml Element'. I need a solution that will work for any type. Please help.
Working...