vokeExpression invokeSave = new CodeMethodInvokeExpression(m_XmlExpression, "Save",
m_XmlFileExpression);
CodeStatementCollection statements = new CodeStatementCollection();
statements.Add(invokeLoadXml);
statements.Add(invokeSave);
// 产生if语句: "if (System.IO.File.Exists(m_XmlFile)) else "
CodeConditionStatement ifStatement = new CodeConditionStatement(new CodeMethodInvokeExpression(
new CodeVariableReferenceExpression("System.IO.File"), "Exists", m_XmlFileExpression), new CodeStatement { } ,
new CodeStatement { statements[0], statements });
// 产生 "m_xml.Load(m_XmlFile);"
CodeMethodInvokeExpression invokeLoad = new CodeMethodInvokeExpression(m_XmlExpression, "Load",
m_XmlFileExpression);
// 产生 "m_AddFlag = false;"
CodeAssignStatement assignAddFalse = new CodeAssignStatement(m_AddFlagExpression,
new CodePrimitiveExpression(false));
constructor.Statements.Add(assignXmlFile);
constructor.Statements.Add(ifStatement);
constructor.Statements.Add(invokeLoad);
constructor.Statements.Add(assignAddFalse);
m_Class.Members.Add(constructor);
}
七、Add和Save方法生成
Add方法只有一条语句,功能是将m_AddFlag设为true,以使数据表类处于加入状态。Save方法比较复杂。它的功能是当m_AddFlag为true时在数据表文件的最后加入一条记录,并保存。具体实现代码如下:
private void GenerateMethods()
{
CodeTypeReference voidReference = new CodeTypeReference("System.void");
//产生Add方法
CodeMemberMethod add = new CodeMemberMethod();
add.ReturnType = voidReference;
add.Name = "add";
add.Attributes = MemberAttributes.Public | MemberAttributes.Final;
CodeAssignStatement assignAddTrue = new CodeAssignStatement(m_AddFlagExpression,
new CodePrimitiveExpression(true));
add.Statements.Add(assignAddTrue);
m_Class.Members.Add(add);
//产生Save方法
CodeMemberMethod save = new CodeMemberMethod();
save.ReturnType = voidReference;
&