开发者

C# code generation

i'm about to make a graduation project application this application is gonna some way receive a description for a situation开发者_JS百科 , and then accordingly generate c# code

i want to know in what field i need to search or how to autogenerate C# code


Have a look at Kathleen Dollard's book on this if you can. She has a website for this topic as well.

You have three options essentially:

Brute-force - creating the code files yourself in a text file

CodeDOM generation - MS's built in way of creating code.

XSLT - What Kathleen uses.


T4 templates can help too -

http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx

And you could also generate IL on the fly. ;)


CodeDOM

I've done a wrapper around codedom. You only need to create your own C# script and specify the types being used.

Example

public interface IWorld
{
    string Hello(string value);
}

string code = @"namespace MyNamespace
{
  class Temp : IWorld
  {
      public string Hello(string value)
      {
          return "World " + value;
      }
  }
}";

Compiler compiler = new Compiler();
compiler.AddType(typeof(string));
compiler.Compile(code);
var obj = compiler.CreateInstance<IWorld>();
string result = obj.Hello("World!");

Note that it was a long time ago that I wrote it. The example might not work 100%. (The Compiler class do work, the example might use it incorrectly).

Compiler source code: http://fadd.codeplex.com/SourceControl/changeset/view/65227#925984

Reflection.Emit

You can also generate IL using Reflection.Emit: http://msdn.microsoft.com/en-us/library/3y322t50.aspx

It's a bit harder but more flexible, since CodeDOM generates a new Assembly each type you compile code.


There is a set of MatLab tools that generates C/C++ code from state-charts and data-flow diagrams:

Real Time Workshop

Real-Time Workshop Embedded Coder

Stateflow Coder

You should dig into it.

What will be the "description of a solution" in your case?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜