上一篇中有几个例子已经比较复杂地运用了CodeDom,但细分下来还是要总结一下。
    下面是常用的一些代码例子:

    1. //
    2. // Main方法
    3. //
    4. CodeEntryPointMethod main = new CodeEntryPointMethod();
    5. main.Comments.Add(new CodeCommentStatement("Main入口函数"));
    6. main.Name = "Main";
    7. main.Attributes = MemberAttributes.Public | MemberAttributes.Static;
    8. main.ReturnType = new CodeTypeReference("System.Void");
    9. main.CustomAttributes.Add(new CodeAttributeDeclaration("System.STAThreadAttribute"));
    10. main.Statements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(System.Windows.Forms.Application)), "Run"), new CodeExpression[] {
    11. new CodeObjectCreateExpression(new CodeTypeReference("Form"))
    12. }));
    13. myDesignerClass.Members.Add(main);
    14. //
    15. // 字段
    16. //
    17. CodeMemberField cmf = new CodeMemberField("System.String", "myName");
    18. cmf.Attributes = MemberAttributes.Private;
    19. cmf.Comments.Add(new CodeCommentStatement("私有字段"));
    20. myDesignerClass.Members.Add(cmf);
    21. //
    22. // 属性
    23. //
    24. CodeMemberProperty prop = new CodeMemberProperty();
    25. prop.Name = "MyAttribute";
    26. prop.Comments.Add(new CodeCommentStatement("属性"));
    27. prop.Attributes = MemberAttributes.Public;
    28. prop.Type = new CodeTypeReference("System.String");
    29. prop.GetStatements.Add(new CodeMethodReturnStatement(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "sName")));
    30. prop.SetStatements.Add(new CodeAssignStatement(
    31. new CodePropertyReferenceExpression(
    32. new CodeThisReferenceExpression(), "sName"),
    33. new CodeArgumentReferenceExpression("value")));
    34. myDesignerClass.Members.Add(prop);
    35. //
    36. //方法
    37. //
    38. CodeMemberMethod cmm = new CodeMemberMethod();
    39. cmm.Name = "MyFunction";
    40. cmm.Comments.Add(new CodeCommentStatement("成员方法"));
    41. cmm.ReturnType = new CodeTypeReference("System.Boolean");
    42. cmm.Attributes = MemberAttributes.Public;
    43. myDesignerClass.Members.Add(cmm);
    44. //方法的参数
    45. CodeParameterDeclarationExpression paraDeclaration = new CodeParameterDeclarationExpression("System.String", "name");
    46. cmm.Parameters.Add(paraDeclaration);
    47. //参数声明表达式
    48. CodeParameterDeclarationExpression paraInt = new CodeParameterDeclarationExpression("System.Int32", "index");
    49. CodeParameterDeclarationExpression paraStr = new CodeParameterDeclarationExpression(new CodeTypeReference("System.String"), "name");
    50. cmm.Parameters.Add(paraInt);
    51. cmm.Parameters.Add(paraStr);
    52. //基元数据表达式,一般用来表示常量
    53. CodeExpression constStr = new CodePrimitiveExpression("Hello World");
    54. cmm.Statements.Add(constStr);
    55. //this引用表达式
    56. CodeExpression thisRef = new CodeThisReferenceExpression();
    57. cmm.Statements.Add(thisRef);
    58. //引用父类表达式
    59. CodeExpression baseRef = new CodeBaseReferenceExpression();
    60. cmm.Statements.Add(baseRef);
    61. //运算表达式
    62. CodeExpression calc = new CodeBinaryOperatorExpression(new CodePrimitiveExpression(3), CodeBinaryOperatorType.Multiply, new CodePrimitiveExpression(4));
    63. cmm.Statements.Add(calc);
    64. //对象表达式
    65. CodeExpression objValue = new CodeObjectCreateExpression(new CodeTypeReference("People"), new CodeExpression[] { new CodePrimitiveExpression("ZhangSan") });
    66. cmm.Statements.Add(objValue);
    67. //数组表达式
    68. CodeExpression strArr = new CodeArrayCreateExpression("System.String", new CodeExpression[] { new CodePrimitiveExpression("ZhangSan"), new CodePrimitiveExpression("LiSi") });
    69. cmm.Statements.Add(strArr);
    70. CodeExpression intArr = new CodeArrayCreateExpression("System.Int32", 4);
    71. cmm.Statements.Add(intArr);
    72. //引用类型表达式
    73. CodeExpression obj = new CodeTypeReferenceExpression("myObj");
    74. cmm.Statements.Add(obj);
    75. //索引表达式
    76. CodeExpression objIdx = new CodeIndexerExpression(new CodeTypeReferenceExpression("myObj"), new CodeSnippetExpression("index"));
    77. cmm.Statements.Add(objIdx);
    78. //数组索引表达式
    79. CodeExpression arrIdx = new CodeArrayIndexerExpression(new CodeTypeReferenceExpression("MyArr"), new CodeSnippetExpression("2"));
    80. cmm.Statements.Add(arrIdx);
    81. //局部变量表达式
    82. CodeExpression localVal = new CodeVariableReferenceExpression("tempStr");
    83. cmm.Statements.Add(localVal);
    84. //引用字段表达式
    85. CodeExpression field = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("obj"), "mName");
    86. cmm.Statements.Add(field);
    87. CodeExpression prop = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("obj"), "Prop");
    88. cmm.Statements.Add(prop);
    89. //强制类型转换表达式
    90. CodeExpression conv = new CodeCastExpression(new CodeTypeReference("TargetClass"), new CodePrimitiveExpression("Obj"));
    91. cmm.Statements.Add(conv);
    92. //方法调用表达式
    93. CodeExpression callMethod = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Console"), "WriteLine", new CodePrimitiveExpression("Hello CodeDom!"));
    94. cmm.Statements.Add(callMethod);
    95. CodeExpression callMethod2 = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("List"), "CopyTo", new CodeExpression[] { new CodeSnippetExpression("array"), new CodeSnippetExpression("index") });
    96. cmm.Statements.Add(callMethod2);
    97. //注释语句
    98. CodeStatement comment = new CodeCommentStatement("定义变量并赋初值");
    99. cmm.Statements.Add(comment);
    100. //变量声明语句
    101. CodeStatement strDec = new CodeVariableDeclarationStatement("System.String", "user1", new CodePrimitiveExpression("ZhangSan"));
    102. cmm.Statements.Add(strDec);
    103. CodeStatement strDec2 = new CodeVariableDeclarationStatement("System.String", "user2");
    104. cmm.Statements.Add(strDec2);
    105. //赋值语句
    106. CodeStatement assign = new CodeAssignStatement(new CodeVariableReferenceExpression("user2"), new CodePrimitiveExpression("LiSi"));
    107. cmm.Statements.Add(assign);
    108. CodeStatement dtDec = new CodeVariableDeclarationStatement("System.DateTime", "dt");
    109. cmm.Statements.Add(dtDec);
    110. CodeStatement dtAssign = new CodeAssignStatement(new CodeVariableReferenceExpression("dt"), new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("System.DateTime"), "Now"));
    111. cmm.Statements.Add(dtAssign);
    112. //组合表达式语句
    113. CodeStatement stmt = new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Console"), "WriteLine", new CodeBinaryOperatorExpression(new CodePrimitiveExpression("Hello."), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression("sName"))));
    114. cmm.Statements.Add(stmt);
    115. //函数返回语句
    116. CodeStatement ret = new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("List"), "Contains", new CodeExpression[] { new CodeSnippetExpression("value") }));
    117. cmm.Statements.Add(ret);
    118. CodeStatement ret2 = new CodeMethodReturnStatement(new CodeSnippetExpression("true"));
    119. cmm.Statements.Add(ret2);
    120. //
    121. //条件语句,仅支持if...else...不支持if...else if...else...
    122. //
    123. CodeConditionStatement cstif = new CodeConditionStatement();
    124. //设置条件表达式
    125. cstif.Condition = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("sName"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression("ZhangSan"));
    126. //条件为真时的语句
    127. cstif.TrueStatements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("System.Console"), "WriteLine", new CodeExpression[] { new CodePrimitiveExpression("Hello, ZhangSan") })));
    128. //条件为假时的语句
    129. cstif.FalseStatements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("System.Console"), "WriteLine", new CodeExpression[] { new CodePrimitiveExpression("You are not ZhangSan") })));
    130. cmm.Statements.Add(cstif);
    131. //
    132. //循环语句,仅支持for
    133. //
    134. cmm.Statements.Add(new CodeVariableDeclarationStatement("System.Int32", "nSum", new CodePrimitiveExpression(0)));
    135. //生成循环语句
    136. CodeIterationStatement cstfor = new CodeIterationStatement();
    137. //初始声明整型变量i,并初始化为1
    138. cstfor.InitStatement = new CodeVariableDeclarationStatement("System.Int32", "i", new CodePrimitiveExpression(1));
    139. //设置增量语句,每次将变量i加1
    140. cstfor.IncrementStatement = new CodeAssignStatement(new CodeVariableReferenceExpression("i"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1)));
    141. //条件表达式
    142. cstfor.TestExpression = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.LessThanOrEqual, new CodePrimitiveExpression(100));
    143. //循环体
    144. cstfor.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("nSum"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("nSum"), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression("i"))));
    145. cmm.Statements.Add(cstfor);

    可生成的C#代码如下:

    1. // Main入口函数
    2. [System.STAThreadAttribute()]
    3. public static void Main()
    4. {
    5. System.Windows.Forms.Application.Run(new CreateCodeTest());
    6. }
    7. // 私有字段
    8. private string myName;
    9. // 属性
    10. public virtual string MyAttribute
    11. {
    12. get
    13. {
    14. return this.sName;
    15. }
    16. set
    17. {
    18. this.sName = value;
    19. }
    20. }
    21. // 成员方法
    22. public virtual bool MyFunction(int index, string name)
    23. {
    24. "Hello World";
    25. this;
    26. base;
    27. (3 * 4);
    28. new People("ZhangSan");
    29. new string[] {
    30. "ZhangSan",
    31. "LiSi"};
    32. new int[4];
    33. myObj;
    34. myObj[index];
    35. MyArr[2];
    36. tempStr;
    37. obj.mName;
    38. obj.Prop;
    39. ((TargetClass)("Obj"));
    40. Console.WriteLine("Hello CodeDom!");
    41. List.CopyTo(array, index);
    42. // 定义变量并赋初值
    43. string user1 = "ZhangSan";
    44. string user2;
    45. user2 = "LiSi";
    46. System.DateTime dt;
    47. dt = System.DateTime.Now;
    48. Console.WriteLine(("Hello." + sName));
    49. return List.Contains(value);
    50. return true;
    51. if ((sName == "ZhangSan"))
    52. {
    53. System.Console.WriteLine("Hello, ZhangSan");
    54. }
    55. else
    56. {
    57. System.Console.WriteLine("You are not ZhangSan");
    58. }
    59. int nSum = 0;
    60. for (int i = 1; (i <= 100); i = (i + 1))
    61. {
    62. nSum = (nSum + i);
    63. }
    64. }

    上面提到仅支持for循环以及if…else…,至于while循环可写成for(;;)形式,else里面又可以放if…else…。
    当然也有说法可以使用CodeSnippetExpression写出while循环以及if…else if…else这样的条件语句,但其实已失去了所谓的“CodeDom”精神。
    究竟是为什么才使用CodeDom的呢?
    ————————————————
    版权声明:本文为CSDN博主「莱昂纳多达芬奇」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/davinciyxw/article/details/7767103