74 lines
2.6 KiB
C#
74 lines
2.6 KiB
C#
using System;
|
|
using System.CodeDom;
|
|
using System.CodeDom.Compiler;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using System.Reflection.Emit;
|
|
using System.Runtime.Serialization.Formatters.Binary;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace FirstVillain.ClassBuild
|
|
{
|
|
public class ClassBuilder
|
|
{
|
|
private string _className;
|
|
private CodeCompileUnit targetUnit;
|
|
private CodeTypeDeclaration targetClass;
|
|
|
|
public ClassBuilder(string className)
|
|
{
|
|
_className = className;
|
|
targetUnit = new CodeCompileUnit();
|
|
CodeNamespace namespaceTarget = new CodeNamespace("FirstVillain.Entities");
|
|
//namespaceTarget.Imports.Add(new CodeNamespaceImport("System")); //import도 가능...리스트 넣으면 추가해야함.
|
|
|
|
targetClass = new CodeTypeDeclaration(_className);
|
|
targetClass.IsClass = true;
|
|
targetClass.TypeAttributes = TypeAttributes.Public | TypeAttributes.Serializable;
|
|
namespaceTarget.Types.Add(targetClass);
|
|
targetUnit.Namespaces.Add(namespaceTarget);
|
|
}
|
|
public void CreateCode(Dictionary<string, Type> map, string path)
|
|
{
|
|
foreach (var typeData in map)
|
|
{
|
|
AddField(typeData.Key, typeData.Value);
|
|
}
|
|
|
|
GenerateCSharpCode(path);
|
|
}
|
|
|
|
private void GenerateCSharpCode(string path)
|
|
{
|
|
string fileName = Path.Combine(path, _className + ".cs");
|
|
if (File.Exists(fileName))
|
|
{
|
|
File.Delete(fileName);
|
|
}
|
|
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
|
|
CodeGeneratorOptions options = new CodeGeneratorOptions();
|
|
options.BracingStyle = "C";
|
|
using (StreamWriter sourceWriter = new StreamWriter(fileName))
|
|
{
|
|
provider.GenerateCodeFromCompileUnit(
|
|
targetUnit, sourceWriter, options);
|
|
}
|
|
}
|
|
|
|
private void AddField(string name, Type type)
|
|
{
|
|
// Declare the widthValue field.
|
|
CodeMemberField fieldValue = new CodeMemberField();
|
|
fieldValue.Attributes = MemberAttributes.Public;
|
|
fieldValue.Name = name;
|
|
fieldValue.Type = new CodeTypeReference(type);
|
|
//widthValueField.Comments.Add(new CodeCommentStatement(
|
|
// "The width of the object."));
|
|
targetClass.Members.Add(fieldValue);
|
|
}
|
|
}
|
|
}
|