今天上課的時候,出於興趣,自己要搭建的框架需要數據庫返回的類爲傳參類型,要用到數據庫的列爲成員變量,所以就花了一節課時間寫了一個簡單類生成器
直接上代碼
、
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);
}
}
}