.Net Version 4.5.1
Very Brief Background
I have a console application where the user enters a function and parameters. Rather than adding supported functions to a dictionary of some kind, I'd like to just have it call the method by name, using the method signature to validate the parameters. I can gather all the information I need in theory, but can't figure out how to CALL the expression.
I think I know why--it's because I can't figure out how to coerce my parameters into a form the Expression.Call line will accept. I tried using the ParameterExpression class, but it doesn't seem to contain the values, only the types and names.
What I Want to Do
-
-
-
-
-
-
- public void Execute(string methodName, object[] args)
- {
-
- MethodInfo method = GetMethodByName(methodName);
-
-
- object[] parameters;
- if (!GetAndValidateParams(
- method.GetParameters().Select(pd => pd.ParameterType).ToArray(),
- args,
- out parameters))
- return;
-
-
- Expression.Call(method, parameters);
- }
I would also be happy with the ability to "assemble" a method call, like in this pseudocode:
- MethodCall mc = new MethodCall(methodInfo);
- mc.ClassInstance = this;
- mc.Parameters.AddRange(parameters);
- mc.Execute();
Thank you in advance for any help or guidance you can provide!
Daniel
Just in Case: The Validation Method
-
- private bool GetAndValidateParams(Type[] expected, object[] args, out object[] convertedArgs)
- {
- Console.Write("Validating parameters...");
-
-
- convertedArgs = null;
- Type[] supportedTypes = new Type[] { typeof(decimal), typeof(string), typeof(int) };
- if (expected.Any(t => !supportedTypes.Any(st => t == st))) return false;
-
- if (expected == null) return false;
- if (expected.Count() == 0 && (args == null || args.Count() == 0))
- {
- Console.Write("Success.\r\n");
- return true;
- }
- convertedArgs = new object[args.Count()];
- for (int x = 0; x < expected.Count(); x++)
- {
-
- if (x > (args.Count() - 1)) return false;
-
-
- try { convertedArgs[x] = Convert.ChangeType(args[x], expected[x]); }
- catch {return false;}
- }
-
-
- Console.Write("Success.\r\n");
- return true;
- }