Dynamiclly Determine Type of Parameter and Type Cast it (code insi

G

Guest

Hello,

Here's a little background. I have a function that calls a method of another
assembly (COM Interop) dynamically through Reflection. It gets method name
and array of values and calls .InvokeMember to get results. Everything worked
fine until parameters types of Boolean and DateTime appeared, it caused Type
mismatch exception. So I decided to explicitlly convert to Bool and DateTime,
however it would not work, only Bool.Parse() and DateTime.Parse seems to work.
But I still want to have a better way of handling it...
Considering my code snippet bellow, could you help me with the following
questions:
1. Is there a way to dynamically get "String representation" of a type that
could be used in a Switch case statement.
2. Why type.Fullname returns "System.Boolean&" what's & charecter doing
there at the end of string
3. Is the code below the best way to handle this task?


/**********Code snippet*****/
Assembly asm = Assembly.Load("Interop.Project1");
//create new instance of class
Type type = asm.GetType("Project1.Class1Class");


object t1 = Activator.CreateInstance(type);
object result;

ParameterModifier[] paramMod = new ParameterModifier[1];
ParameterModifier mod = new ParameterModifier(3);
mod[0] = false;
mod[1] = true;
mod[2] = true;
paramMod[0] = mod;

object[] argList = new object[3];
argList[0] = "some string";
argList[1] = "False";
argList[2] = "5/13/2006";

//get Method Info and Parameter info
MethodInfo mInfo = type.GetMethod("doA");
ParameterInfo[] paramsInfo = mInfo.GetParameters();

//Type paramType = paramsInfo[2].ParameterType;

for (int i=0;i<paramsInfo.Length;i++)
{

switch (paramsInfo.ParameterType.FullName )
{
case "System.Boolean&" :
argList = Boolean.Parse(argList.ToString());
break;
case "System.DateTime&" :
argList = DateTime.Parse(argList.ToString());
break;
default:
argList = System.Convert.ChangeType(argList,
paramsInfo.ParameterType);
break;
}

}


//invoke the method name passed m
result = type.InvokeMember("doA",
BindingFlags.InvokeMethod,
null,
t1,
argList, paramMod, null, null);
 
N

Nicholas Paldino [.NET/C# MVP]

Lenn,

I would check against the type directly, like this:

if (paramsInfo.ParameterType == typeof(bool))
{
// Perform your logic here.
}

However, I probably would just make a call to ConvertType every time for
this, since you just want to convert between simple types it seems.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top