The CodeDOM provides types that represent many common types of source code elements. You can design a program that builds a source code model using CodeDOM elements to assemble an object graph. This object graph can be rendered as source code using a CodeDOM code generator for a supported programming language. The CodeDOM can also be used to compile source code into a binary assembly.
This article contains some helper methods you can use to create a class using CodeDOM.
Creating a namespace
private CodeNamespace CreateNameSpace(String name)
{
CodeNamespace CurrentNameSpace = new CodeNamespace(name);
CurrentNameSpace.Imports.Add(new CodeNamespaceImport("System"));
CurrentNameSpace.Imports.Add(new CodeNamespaceImport("System.Text"));
CurrentNameSpace.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
CurrentNameSpace.Imports.Add(new CodeNamespaceImport("System.IO"));
CurrentNameSpace.Imports.Add(new CodeNamespaceImport("System.Collections.Specialized"));
CurrentNameSpace.Imports.Add(new CodeNamespaceImport("System.Collections.ObjectModel"));
return CurrentNameSpace;
}
Or
private CodeNamespace CreateNameSpace(String name, CodeNamespaceImport[] imports)
{
CodeNamespace CurrentNameSpace = new CodeNamespace(name);
CurrentNameSpace.Imports.AddRange(imports);
return CurrentNameSpace;
}
Creating a class
private CodeTypeDeclaration CreateClass(String className)
{
CodeTypeDeclaration ctd = new CodeTypeDeclaration(className);
ctd.IsClass = true;
ctd.Attributes = MemberAttributes.Public;
return ctd;
}
Creating class variables
private CodeMemberField CreateClassVariable(System.Type type, String name)
{
CodeMemberField classVariable = new CodeMemberField(type, name);
classVariable.Attributes = MemberAttributes.Private;
return classVariable;
}
Create Properties
private CodeMemberProperty CreateClassProperty(Boolean isReadOnly, String name, Type type, String variableName)
{
CodeMemberProperty property = new CodeMemberProperty();
property.Name = name;
property.Type = new CodeTypeReference(type);
property.Attributes = MemberAttributes.Public;
property.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), variableName)));
if(!isReadOnly)
property.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), variableName), new CodePropertySetValueReferenceExpression()));
return property;
}
Creating methods
private CodeMemberMethod CreateMethod(String methodName, CodeTypeReference returnType, CodeParameterDeclarationExpressionCollection methodParams, MemberAttributes accessModifier)
{
CodeMemberMethod method = new CodeMemberMethod();
method.Name = methodName;
method.ReturnType = returnType;
method.Parameters.AddRange(methodParams);
method.Attributes = accessModifier;
return method;
}
No comments:
Post a Comment