c# - Evaluate expression as string, return object? -
basically have code when happens, need set object equal expression. of "what do" jazz stored string. parse it, , use reflection find object doing to. need find out how store value object. problem value "1", "1*(5/2)", or "some string value". cool if have expressions "this.someproperty" or "(x > 3 ? 4 : 5)".
also, object storing to, string, int, double, or float @ minimum.
the vs2008 samples included nifty expressionparser used generic expression parser (vs2008 samples). few small updates, , custom factory class, can turn bit more expressive:
string expression = "(1 + 2)"; var func = functionfactory.create<int>(expression); or:
expression = "(a * b)"; var func2 = functionfactory.create<int, int, int>(expression, new[] { "a", "b" }); the return types of these create methods func<> instances, means nice type delegates:
int result = func2(45, 100); // result = 450; i've push code gist
update: i've blogged this too.
update 2, example:
var person = new person { age = 5 }; string expression = "(age == 5)"; var func3 = functionfactory.create<person, bool>(expression); bool isfive = func3(person); // should true.
Comments
Post a Comment