今天上课的时候,出于兴趣,自己要搭建的框架需要数据库返回的类为传参类型,要用到数据库的列为成员变量,所以就花了一节课时间写了一个简单类生成器
直接上代码
、
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ClassCreater
{
class Program
{
static void Main(string[] args)
{
//命名空间
string Namespace = "LINQ";
//类名
string ClassName = "Ac";
string filePath = @"E:\C#\高级C#作业\LINQ\LINQ\SQLEntity\";//类生成到的文件路径
//成员变量 每个字符串的格式为属性名-类型名 如StudentName-string string可以省略 直接写StudentName 其他不能
string[] pro = { "AcademyID", "AcademyCode-int", "AcademyName" };
//主函数
creater(Namespace, ClassName,filePath, pro);
}
public static void write(string[] info, Dictionary type)
{
//指定日志文件的目录
string fname = info[2] + info[1] + ".cs";
//定义文件信息对象
FileInfo finfo = new FileInfo(fname);
//判断文件是否存在以及是否大于2K
if (finfo.Exists)
{
//删除该文件
finfo.Delete();
}
//创建只写文件流
using (FileStream fs = finfo.OpenWrite())
{
//根据上面创建的文件流创建写数据流
StreamWriter w = new StreamWriter(fs);
//设置写数据流的起始位置为文件流的末尾
w.BaseStream.Seek(0, SeekOrigin.End);
w.Write("using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;");
w.Write("\nnamespace " + info[0] + "\n{");
w.Write("\n public class " + info[1] + " {");
foreach (var yu in type)
{
w.Write("\n public " + yu.Value + " " + yu.Key + " { get; set; }");
}
w.Write("\n }\n}");
w.Flush();
//关闭写数据流
w.Close();
}
}
public static Dictionary StrToDic(string[] pro)
{
Dictionary list = new Dictionary();
foreach (var str in pro)
{
string[] ccc = str.Split('-');
if (ccc.Length == 1)
{
list.Add(ccc[0], "string");
}
else
{
list.Add(ccc[0], ccc[1]);
}
}
return list;
}
public static void creater(string Namespace, string ClassName,string filePath, string[] pro)
{
Dictionary yu = StrToDic(pro);//成员变量
string[] info = { Namespace, ClassName,filePath };//命名空间,Class类名,存储路径
write(info, yu);
}
}
}