we need to evaluate a value in an object in run time while we have a textual statement of the exact member path for example: myobject.firstMember.secondMember[3].text
we thought of parsing this textual statement using regex and then evaluate the text value by using reflection but before we do that i wonder if C# support some kind of eval ability? so we won't have to do the parsing ourself. How do microsoft do this in their immediate window or watch windows?
thanks you very much,
Adi Barda
Probably the easiest way is to use DataBinder.Eval from System.Web.UI:
var foo = new Foo() { Bar = new Bar() { Value = "Value" } }; var value = DataBinder.Eval(foo, "Bar.Value");
I have written an open source project, Dynamic Expresso, that can convert text expression written using a C# syntax into delegates (or expression tree). Expressions are parsed and transformed into Expression Trees without using compilation or reflection.
You can write something like:
var interpreter = new Interpreter(); var result = interpreter.Eval("8 / 2 + 2");
or
var interpreter = new Interpreter() .SetVariable("service", new ServiceExample()); string expression = "x > 4 ? service.SomeMethod() : service.AnotherMethod()"; Lambda parsedExpression = interpreter.Parse(expression, new Parameter("x", typeof(int))); parsedExpression.Invoke(5);
My work is based on Scott Gu article http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With