C#代码生成器实现原理
1、目的
分别用代码、模板生成目标代码文件。
犯法主要包括文件读写、代码生成函数、及应用程序。
2、文件读写函数
/// <summary>
/// 文本文件写
/// </summary>
/// <param name="path"></param>
/// <param name="str"></param>
public static void WriteTxt(string path, string str)
{
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine(str);
writer.Close();
}
}
/// <summary>
/// 文本文件读
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string ReadTxt(string path)
{
try
{
if (!File.Exists(path))
{
return null;
}
string str = string.Empty;
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
using (StreamReader sr = new StreamReader(fs))
{
str=sr.ReadToEnd();
sr.Close();
}
fs.Close();
}
return str;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
3、代码生成函数
/// <summary>
/// 代码生成器(整体生成)
/// </summary>
/// <param name="space"></param>
/// <param name="name"></param>
public static void CsharpGenerate(string space,string name)
{
StringBuilder sb = new StringBuilder();
sb.Append("using System;\n" +
$"namespace {space}\n" +
"{\n" +
$" public class {name}" +
" {\n" +
" private string name;\n" +
" public void function(string str)\n" +
" {\n" +
" Console.WriteLine(str);\n" +
" }\n" +
" }\n"+
"}\n");
WriteTxt("E:\\generate.cs", sb.ToString());
}
/// <summary>
/// 代码生成器(分行生成)
/// </summary>
/// <param name="space"></param>
/// <param name="name"></param>
public static void CsharpGenerateSplit(string space, string name)
{
StringBuilder sb = new StringBuilder();
sb.Append("using System;\n");
sb.Append($"namespace {space}\n");
sb.Append("{\n");
sb.Append($" public class {name}");
sb.Append(" {\n");
sb.Append(" private string name;\n");
sb.Append(" public void function(string str)\n");
sb.Append(" {\n");
sb.Append(" Console.WriteLine(str);\n");
sb.Append(" }\n");
sb.Append(" }\n");
sb.Append("}\n");
WriteTxt("E:\\generateSplit.cs", sb.ToString());
}
/// <summary>
/// 代码生成器(模板生成)
/// </summary>
/// <param name="space"></param>
/// <param name="name"></param>
public static void CsharpGenerateTemplate(string space, string name)
{
string str = ReadTxt("E:\\generate.cs");
str = str.Replace("Demo", space);
str = str.Replace("Test", name);
WriteTxt("E:\\generateTemplate.cs", str);
}
4、应用
static void Main(string[] args)
{
//CsharpGenerate("Demo", "Test");
//CsharpGenerateSplit("Demo", "Test");
CsharpGenerateTemplate("Nature", "Develop");
}
5、效果
generate.cs文件
using System;
namespace Demo
{
public class Test {
private string name;
public void function(string str)
{
Console.WriteLine(str);
}
}
}
generateSplit.cs文件
using System;
namespace Demo
{
public class Test {
private string name;
public void function(string str)
{
Console.WriteLine(str);
}
}
}
generateTemplate.cs文件
using System;
namespace Nature
{
public class Develop {
private string name;
public void function(string str)
{
Console.WriteLine(str);
}
}
}