I need to know if there is any library out there that will allow me to, given a certain string representing a mathematical function, say, x^2+x+1
, (don't care about how the string format, any will work for me) generates a C# func that will represent said function.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- Correctly parse PDF paragraphs with Python
- Keeping track of variable instances
You can use the CSharpCodeProvider class to compile code to a file/assembly and dynamically load the compiled assembly. Using the compiler from your program is described here. This Stackoverflow questions shows how to load the compiled assembly. Keep in mind that you need to wrap your function in a class to load and execute it later on.
Alternatively you can use CS-Script to do the dirty assembly compiling, loading and executing job.
You can use the CodeDOM to dynamic compile a type, about this, here you can find a fluent interface to simply the writing of the code, e.g:
I've to release on CodePlex a better fluent interface API that will use Roslyn also when it will be released in RTM.
Take a look at the Roslyn API. It will allow you to compile strings at runtime
Been using FLEE (Fast Lightweight Expression Evaluator) for a while now and it's been working great. They have a version that maintains most functionality for Silverlight as well. It's designed to do pretty much exactly what you're asking for and more.
http://flee.codeplex.com/
Given your example from your comment to evaluate
x^2+x+1
(written in Notepad):This looks like a nice solution. Of course, it also can be solved with the usage of Expression Trees and a parse from strings to expressions, which later can be compiled (in run time), and executed.