I think you need to explain your design a bit before I can help any further. There are several type-safe ways to do what you want. However your statements so far have only shown me that you want a way to pass any parameters to a function of any type and any number but the type and number of params is not known. This cannot be done in any object-oriented language because it is far too generic to be useful.
My suggestion is this:
- Store the types that the function expects and the order it expects them in (IE: the method signature)
- Create an interface for your parameters so you can get their type, value, etc
- Create an interface to the collection and implement the interface to get access to the parameters
- Pass an instance of the interface to the collection to the API function
- Parse the collection and type check using typeof() against the types stored in the function types collection you created in the first step. If the types don't match then you can bail or inform the caller or whatever you want to do. If they do match then you proceed.
Code:
bool paramTypeMismatch = false;
int paramCount = 0;
foreach (Param p in Collection)
{
if (p.GetType() != StoredFunctionTypes[paramCount])
{
paramTypeMismatch = true;
break;
}
++paramCount;
}
if (!paramTypeMismatch)
{
// Execute function using collection information (parameters)
}
else
{
// Incorrect parameter types passed or they are in the wrong order
}
You will still have to switch on type at some point to do the actual cast:
Code:
if (p.GetType() == typeof(Single))
{
float value = (float)p.GetValue();
}
Or you can do this:
Code:
try
{
float value = (float)p.GetValue();
}
catch (System.InvalidCastException e)
{
// p.GetValue() is not a float
}