本文章来自于msdn,对想做自动代码生成器的朋友有好处!

    1. using System;
    2. using System.Reflection;
    3. using System.IO;
    4. using System.CodeDom;
    5. using System.CodeDom.Compiler;
    6. using Microsoft.CSharp;
    7. namespace SampleCodeDom
    8. {
    9. /// <summary>
    10. /// This code example creates a graph using a CodeCompileUnit and
    11. /// generates source code for the graph using the CSharpCodeProvider.
    12. /// </summary>
    13. class Sample
    14. {
    15. /// <summary>
    16. /// Define the compile unit to use for code generation.
    17. /// </summary>
    18. CodeCompileUnit targetUnit;
    19. /// <summary>
    20. /// The only class in the compile unit. This class contains 2 fields,
    21. /// 3 properties, a constructor, an entry point, and 1 simple method.
    22. /// </summary>
    23. CodeTypeDeclaration targetClass;
    24. /// <summary>
    25. /// The name of the file to contain the source code.
    26. /// </summary>
    27. private const string outputFileName = "SampleCode.cs";
    28. /// <summary>
    29. /// Define the class.
    30. /// </summary>
    31. public Sample()
    32. {
    33. targetUnit = new CodeCompileUnit();
    34. CodeNamespace samples = new CodeNamespace("CodeDOMSample");
    35. samples.Imports.Add(new CodeNamespaceImport("System"));
    36. targetClass = new CodeTypeDeclaration("CodeDOMCreatedClass");
    37. targetClass.IsClass = true;
    38. targetClass.TypeAttributes =
    39. TypeAttributes.Public | TypeAttributes.Sealed;
    40. samples.Types.Add(targetClass);
    41. targetUnit.Namespaces.Add(samples);
    42. }
    43. /// <summary>
    44. /// Adds two fields to the class.
    45. /// </summary>
    46. public void AddFields()
    47. {
    48. // Declare the widthValue field.
    49. CodeMemberField widthValueField = new CodeMemberField();
    50. widthValueField.Attributes = MemberAttributes.Private;
    51. widthValueField.Name = "widthValue";
    52. widthValueField.Type = new CodeTypeReference(typeof(System.Double));
    53. widthValueField.Comments.Add(new CodeCommentStatement(
    54. "The width of the object."));
    55. targetClass.Members.Add(widthValueField);
    56. // Declare the heightValue field
    57. CodeMemberField heightValueField = new CodeMemberField();
    58. heightValueField.Attributes = MemberAttributes.Private;
    59. heightValueField.Name = "heightValue";
    60. heightValueField.Type =
    61. new CodeTypeReference(typeof(System.Double));
    62. heightValueField.Comments.Add(new CodeCommentStatement(
    63. "The height of the object."));
    64. targetClass.Members.Add(heightValueField);
    65. }
    66. /// <summary>
    67. /// Add three properties to the class.
    68. /// </summary>
    69. public void AddProperties()
    70. {
    71. // Declare the read-only Width property.
    72. CodeMemberProperty widthProperty = new CodeMemberProperty();
    73. widthProperty.Attributes =
    74. MemberAttributes.Public | MemberAttributes.Final;
    75. widthProperty.Name = "Width";
    76. widthProperty.HasGet = true;
    77. widthProperty.Type = new CodeTypeReference(typeof(System.Double));
    78. widthProperty.Comments.Add(new CodeCommentStatement(
    79. "The Width property for the object."));
    80. widthProperty.GetStatements.Add(new CodeMethodReturnStatement(
    81. new CodeFieldReferenceExpression(
    82. new CodeThisReferenceExpression(), "widthValue")));
    83. targetClass.Members.Add(widthProperty);
    84. // Declare the read-only Height property.
    85. CodeMemberProperty heightProperty = new CodeMemberProperty();
    86. heightProperty.Attributes =
    87. MemberAttributes.Public | MemberAttributes.Final;
    88. heightProperty.Name = "Height";
    89. heightProperty.HasGet = true;
    90. heightProperty.Type = new CodeTypeReference(typeof(System.Double));
    91. heightProperty.Comments.Add(new CodeCommentStatement(
    92. "The Height property for the object."));
    93. heightProperty.GetStatements.Add(new CodeMethodReturnStatement(
    94. new CodeFieldReferenceExpression(
    95. new CodeThisReferenceExpression(), "heightValue")));
    96. targetClass.Members.Add(heightProperty);
    97. // Declare the read only Area property.
    98. CodeMemberProperty areaProperty = new CodeMemberProperty();
    99. areaProperty.Attributes =
    100. MemberAttributes.Public | MemberAttributes.Final;
    101. areaProperty.Name = "Area";
    102. areaProperty.HasGet = true;
    103. areaProperty.Type = new CodeTypeReference(typeof(System.Double));
    104. areaProperty.Comments.Add(new CodeCommentStatement(
    105. "The Area property for the object."));
    106. // Create an expression to calculate the area for the get accessor
    107. // of the Area property.
    108. CodeBinaryOperatorExpression areaExpression =
    109. new CodeBinaryOperatorExpression(
    110. new CodeFieldReferenceExpression(
    111. new CodeThisReferenceExpression(), "widthValue"),
    112. CodeBinaryOperatorType.Multiply,
    113. new CodeFieldReferenceExpression(
    114. new CodeThisReferenceExpression(), "heightValue"));
    115. areaProperty.GetStatements.Add(
    116. new CodeMethodReturnStatement(areaExpression));
    117. targetClass.Members.Add(areaProperty);
    118. }
    119. /// <summary>
    120. /// Adds a method to the class. This method multiplies values stored
    121. /// in both fields.
    122. /// </summary>
    123. public void AddMethod()
    124. {
    125. // Declaring a ToString method
    126. CodeMemberMethod toStringMethod = new CodeMemberMethod();
    127. toStringMethod.Attributes =
    128. MemberAttributes.Public | MemberAttributes.Override;
    129. toStringMethod.Name = "ToString";
    130. toStringMethod.ReturnType =
    131. new CodeTypeReference(typeof(System.String));
    132. CodeFieldReferenceExpression widthReference =
    133. new CodeFieldReferenceExpression(
    134. new CodeThisReferenceExpression(), "Width");
    135. CodeFieldReferenceExpression heightReference =
    136. new CodeFieldReferenceExpression(
    137. new CodeThisReferenceExpression(), "Height");
    138. CodeFieldReferenceExpression areaReference =
    139. new CodeFieldReferenceExpression(
    140. new CodeThisReferenceExpression(), "Area");
    141. // Declaring a return statement for method ToString.
    142. CodeMethodReturnStatement returnStatement =
    143. new CodeMethodReturnStatement();
    144. // This statement returns a string representation of the width,
    145. // height, and area.
    146. string formattedOutput = "The object:" + Environment.NewLine +
    147. " width = {0}," + Environment.NewLine +
    148. " height = {1}," + Environment.NewLine +
    149. " area = {2}";
    150. returnStatement.Expression =
    151. new CodeMethodInvokeExpression(
    152. new CodeTypeReferenceExpression("System.String"), "Format",
    153. new CodePrimitiveExpression(formattedOutput),
    154. widthReference, heightReference, areaReference);
    155. toStringMethod.Statements.Add(returnStatement);
    156. targetClass.Members.Add(toStringMethod);
    157. }
    158. /// <summary>
    159. /// Add a constructor to the class.
    160. /// </summary>
    161. public void AddConstructor()
    162. {
    163. // Declare the constructor
    164. CodeConstructor constructor = new CodeConstructor();
    165. constructor.Attributes =
    166. MemberAttributes.Public | MemberAttributes.Final;
    167. // Add parameters.
    168. constructor.Parameters.Add(new CodeParameterDeclarationExpression(
    169. typeof(System.Double), "width"));
    170. constructor.Parameters.Add(new CodeParameterDeclarationExpression(
    171. typeof(System.Double), "height"));
    172. // Add field initialization logic
    173. CodeFieldReferenceExpression widthReference =
    174. new CodeFieldReferenceExpression(
    175. new CodeThisReferenceExpression(), "widthValue");
    176. constructor.Statements.Add(new CodeAssignStatement(widthReference,
    177. new CodeArgumentReferenceExpression("width")));
    178. CodeFieldReferenceExpression heightReference =
    179. new CodeFieldReferenceExpression(
    180. new CodeThisReferenceExpression(), "heightValue");
    181. constructor.Statements.Add(new CodeAssignStatement(heightReference,
    182. new CodeArgumentReferenceExpression("height")));
    183. targetClass.Members.Add(constructor);
    184. }
    185. /// <summary>
    186. /// Add an entry point to the class.
    187. /// </summary>
    188. public void AddEntryPoint()
    189. {
    190. CodeEntryPointMethod start = new CodeEntryPointMethod();
    191. CodeObjectCreateExpression objectCreate =
    192. new CodeObjectCreateExpression(
    193. new CodeTypeReference("CodeDOMCreatedClass"),
    194. new CodePrimitiveExpression(5.3),
    195. new CodePrimitiveExpression(6.9));
    196. // Add the statement:
    197. // "CodeDOMCreatedClass testClass =
    198. // new CodeDOMCreatedClass(5.3, 6.9);"
    199. start.Statements.Add(new CodeVariableDeclarationStatement(
    200. new CodeTypeReference("CodeDOMCreatedClass"), "testClass",
    201. objectCreate));
    202. // Creat the expression:
    203. // "testClass.ToString()"
    204. CodeMethodInvokeExpression toStringInvoke =
    205. new CodeMethodInvokeExpression(
    206. new CodeVariableReferenceExpression("testClass"), "ToString");
    207. // Add a System.Console.WriteLine statement with the previous
    208. // expression as a parameter.
    209. start.Statements.Add(new CodeMethodInvokeExpression(
    210. new CodeTypeReferenceExpression("System.Console"),
    211. "WriteLine", toStringInvoke));
    212. targetClass.Members.Add(start);
    213. }
    214. /// <summary>
    215. /// Generate CSharp source code from the compile unit.
    216. /// </summary>
    217. /// <param name="filename">Output file name</param>
    218. public void GenerateCSharpCode(string fileName)
    219. {
    220. CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
    221. CodeGeneratorOptions options = new CodeGeneratorOptions();
    222. options.BracingStyle = "C";
    223. using (StreamWriter sourceWriter = new StreamWriter(fileName))
    224. {
    225. provider.GenerateCodeFromCompileUnit(
    226. targetUnit, sourceWriter, options);
    227. }
    228. }
    229. /// <summary>
    230. /// Create the CodeDOM graph and generate the code.
    231. /// </summary>
    232. static void Main()
    233. {
    234. Sample sample = new Sample();
    235. sample.AddFields();
    236. sample.AddProperties();
    237. sample.AddMethod();
    238. sample.AddConstructor();
    239. sample.AddEntryPoint();
    240. sample.GenerateCSharpCode(outputFileName);
    241. }
    242. }
    243. }