Skip to content

Instantly share code, notes, and snippets.

@toptensoftware
Last active October 26, 2016 03:50
Show Gist options
  • Select an option

  • Save toptensoftware/904f14e930c0b1c3e55e5b46bd13dd77 to your computer and use it in GitHub Desktop.

Select an option

Save toptensoftware/904f14e930c0b1c3e55e5b46bd13dd77 to your computer and use it in GitHub Desktop.
public class ReflectionContext : IContext
{
public ReflectionContext(object targetObject)
{
_targetObject = targetObject;
}
object _targetObject;
public double ResolveVariable(string name)
{
// Find property
var pi = _targetObject.GetType().GetProperty(name);
if (pi == null)
throw new InvalidDataException($"Unknown variable: '{name}'");
// Call the property
return (double)pi.GetValue(_targetObject);
}
public double CallFunction(string name, double[] arguments)
{
// Find method
var mi = _targetObject.GetType().GetMethod(name);
if (mi == null)
throw new InvalidDataException($"Unknown function: '{name}'");
// Convert double array to object array
var argObjs = arguments.Select(x => (object)x).ToArray();
// Call the method
return (double)mi.Invoke(_targetObject, argObjs);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment