Dynamic code generation

眉间皱痕 提交于 2019-12-04 08:00:29
glenatron

You my find it is rewarding to look at the Dynamic Language Runtime which is more or less designed for creating high-level languages based on .NET.

It's perhaps also worth looking at some of the previous Stack Overflow threads on Domain Specific Languages which contain some useful links to tools for working with DSLs, which sounds a little like what you are planning although I'm still not absolutely clear from the question what exactly your aim is.

Most things "click and play" should be simple enough just to stick some pre-defined building-block objects together (probably using interfaces on the boundaries). Meaning: you might not need to do dynamic code generation - just "fake it". For example, using property-bag objects (like DataTable etc, although that isn't my first choice) for values, etc.

Another option for dynamic evaluation is the Expression class; especially in .NET 4.0, this is hugely versatile, and allows compilation to a delegate.

Do the C# source generation and don't care about speed until it matters. The C# compiler is quite quick.

When I wrote a dynamic code generator, I relied heavily on System.Reflection.Emit.

Basically, you programatically create dynamic assemblies and add new types to them. These types are constructed using the Emit constructs (properties, events, fields, etc..). When it comes to implementing methods, you'll have to use an ILGenerator to pump out MSIL op-codes into your method. That sounds super scary, but you can use a couple of tools to help:

  • A pre-built sample implementation
  • ILDasm to inspect the op-codes of the sample implementation.

It depends on your requirements, CodeDOM would certainly be the best fit for a "program" stored it in a "data model".

However its unlikely that using option 2 will be in any way measurably slower in comparision with any other approach.

I would echo others in that 1) the compiler is quick, and 2) "Click and Play" things should be simple enough so that no single widget added to a pile of widgets can make it an illegal pile.

Good luck. I'm skeptical that you can achieve point (2) for anything but really toy-level programs.

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