从数据到代码——通过代码生成机制实现强类型编程[下篇]
发布时间:2020-12-16 09:06:14 所属栏目:asp.Net 来源:网络整理
导读:在《上篇》中,我们实现了将保存有消息条目的XML向CodeDOM的转换,即是将XML文件生成一个CodeCompileUnit对象,而该CodeCompileUnit对象反映出来的DOM层次和我们将会生成的代码文件向匹配。在下篇中,我们将实现整个代码生成系统的第二个步骤—— 通过VS的Cu
在《上篇》中,我们实现了将保存有消息条目的XML向CodeDOM的转换,即是将XML文件生成一个CodeCompileUnit对象,而该CodeCompileUnit对象反映出来的DOM层次和我们将会生成的代码文件向匹配。在下篇中,我们将实现整个代码生成系统的第二个步骤——通过VS的Custom Tool实现数据(保存消息条目的XML)向代码文件的自动转换。 一、让MessageCodeGenerator继承BaseCodeGeneratorWithSite在《上篇》我们创建了MessageCodeGenerator类,定义了如下一个BuildCodeObject方法实现将一个XmlDocument转换成一个CodeCompileUnit对象。 1: namespace Artech.CodeDomGenerator 3: public class MessageCodeGenerator 5: // Others...
7: } 2: { 4: { 6: { 8: } 10: { 12: messageDoc.LoadXml(inputFileContent); 14: CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
16: options.BracingStyle = "C";
18: { 20: string code = writer.ToString();
22: byte[] codeBytes = Encoding.Unicode.GetBytes(code);
24: Buffer.BlockCopy(preambleBytes,result,preambleBytes.Length); 26: return result;
28: } 30: string GetDefaultExtension()
32: return ".cs"; 34: } // Setting ComVisible to false makes the types in this assembly not visible 3: // COM,set the ComVisible attribute to true on that type.
1: [Guid("F9A0FCB3-864F-4B87-885B-FAEBC860BD64")]
3: { 5: } 程序集的注册通过命令行工具RegAsm.exe完成,我们只需要启动通过VS 2010的命名行工具,执行RegAsm.exe命令对编译生成的程序集进行注册。 <?xml version="1.0" encoding="utf-8" ?>
3: message id="MandatoryField" value="The {0} is mandatory." category="Validation"/> 5: ="ReallyDelete" ="Do you really want to delete the {0}." ="Confirmation" 6: </> 然后右击该XML文件,在弹出的上下文菜单中选择Properties选项。你会发现在属性对话框中有个叫作Custom Tool的属性名称,在该项上填写上我们的代码生成器的名称:MessageCodeGenerator。 该.cs文件和我们在《上篇》给出的代码一模一样。那么我们就可以借助于生成出来的代码,以一种强类型的方式获取相应的、被格式化的消息文本。 // <auto-generated>
4: // Runtime Version:4.0.30319.1
// Changes to this file may cause incorrect behavior and will be lost if 8: // </auto-generated>
11: 12: {
14: 16: { 18: class Validation
20: 22: 25: 27: { 29: static Artech.CodeDomGenerator.MessageEntry ReallyDelete = "ReallyDelete",1)">"Do you really want to delete the {0}.",1)">"Confirmation"); 31: } 相关内容
推荐文章
站长推荐
热点阅读
|