.net 4 - run code from string - in C# / F# / IronRuby / IronPython

感情迁移 提交于 2019-12-11 10:18:19

问题


What ways do I have in .net to run code from string?

Console.WriteLine(Compile("1 + 2 * 3"));    // results is 7.

What other options do we have?

  • C# - Compile the code on runtime?
  • IronRuby / IronPython?
  • F#?

回答1:


So, the dynamic languages like IronRuby and IronPython make it very easy to do what you want. Create a script engine and execute the string. Easy as that.

C#, it is possible, using the Code DOM... but it it compiles the code every time into a DLL. This is a costly behavior and can cause your app to grow in memory size over time if you don't do some tricky stuff with App Domains. It CAN be done, but I really prefer using IronRuby or IronPython over this approach. It is much more simple.

Finally, in C# 5.0, we are expecting to see the compiler as a managed service. This means you will be able to run eval("//c#code") in the future... but it is not available yet.

Hope it helps!




回答2:


Checkout NCalc. It's a dll you can include in your application and it supports multiple math and logic operations. http://ncalc.codeplex.com/



来源:https://stackoverflow.com/questions/2965597/net-4-run-code-from-string-in-c-sharp-f-ironruby-ironpython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!