ArticleDirectory
Address: http://www.cnblogs.com/hjblog/archive/2012/11/14/2769660.html
ProgramAll members wroteCodeGenerator? To be honest, I have never used a commercial code generator, and I have written it myself. It is nice to use the code generation tool to avoid repetitive work. I have written several times before, and the implementation is very poor, mainly because the template is difficult to write and ugly. Use the razor template this time, because the razor template syntax is more concise than other templates, and the prepared templates look more beautiful. I personally think: the use of the framework cannot replace code generation. The framework only improves productivity with coarse granularity, and code generation can improve coding efficiency in a small aspect.
Template writing:
Let's take a look at the code generation template I wrote here:
< Grid X: Name = "Layoutroot" Background = "White" Width = "400" >
< Grid. columndefinitions >
< Columndefinition Width = "Auto" />
< Columndefinition />
</ Grid. columndefinitions >
< Grid. rowdefinitions >
@ Foreach (column Col in model. columns)
{
<RowdefinitionHeight= "Auto"/>
}
</Grid. rowdefinitions>
@ Foreach (column Col in model. columns)
{
VaR desp = col. Description ?? Col. Name;
< Textblock Text = "@ Desp" Margin = "4" Verticalalignment = "Center" />
< Textbox Text =" {Binding @ col. name} " Grid. Column = "1" Margin = "4" />
}
</ Grid >
This is a template that generates front-end XAML code. It uses loop foreach, bind attributes, and variable definition statements, but the template does not look messy at all. If you use webform's <%> syntax, it will be terrible.
Smart sensing:
The template can be compiled intelligently. As long as we create a text file in Vs, change the extension to cshtml, and re-open it. @ using uses the namespace, then define the model as a strong type. Of course, do not forget to delete the definition statement after writing it. After all, most templates are written at one time, and productivity improvement is also reflected here.
Template parsing:
The razorengine parsing template is simple and the Project address is http://razorengine.codeplex.com /. You only need to reference two DLL files and then call the following statement:
String Result = razor. parse (template, model );
The first parameter is the string format of the template we wrote above. The second parameter is the data context. The returned value is the generated code.
Conclusion:
Writing a simple self-use code generator using the razor template has become a simple and interesting thing.