If it is possible, how could I check if a class exists based upon a string, and if that class does exist get a new instance of that object.
I have this method here that checks if an object has a method.
public static bool HasMethod(object objectToCheck, string methodName)
{
Type type = objectToCheck.GetType();
return type.GetMethod(methodName) != null;
}
Then after that how could I check the parameters that a method takes?
Is this all possible?
Answer
To get the class:
public T GetInstance<T>(string namespace, string type)
{
return (T)Activator.CreateInstance(Type.GetType(namespace + "." + type));
}
To get the method:
public static bool HasMethod(object objectToCheck, string methodName)
{
Type type = objectToCheck.GetType();
return type.GetMethod(methodName) != null;
}
...
dynamic controller = GetInstance<dynamic>(controllerString);
if (HasMethod(controller, actionString))
{
controller.GetType().GetMethod(actionString);
}
To get the parameters
MethodInfo mi = type.GetMethod(methodName);
if (mi != null)
{
ParameterInfo[] parameters = mi.GetParameters();
// The parameters array will contain a list of all parameters
// that the method takes along with their type and name:
foreach (ParameterInfo parameter in parameters)
{
string parameterName = parameter.Name;
Type parameterType = parameter.ParameterType;
}
}