姐妹篇《URL地址记住不咋办,代码生成走一波。》地址:https://blog.youkuaiyun.com/TimChen44/article/details/115582820
“头疼”
Angular框架使用TypeScript,拥有强类型的特点,然后不停从后端吧C#的DTO改造成TS的,好烦😖。有时遇到后端修改了前端还不知道,更烦😖。
“吃药”
作为一个时刻想着如何偷懒的程序员,烦的事情就让计算机去干,所以写一个代码生成工具。
工具代码
public class BuildDtoToTS
{
public static string Build(Assembly assembly)
{
List<DtoClass> dtos = GetDtos(assembly);
string code = CreateCode(dtos);
return code.ToString();
}
public static void BuildToFile(Assembly assembly, string path)
{
var code = Build(assembly);
string existsCode = "";
if (System.IO.File.Exists(path) == true)
existsCode = System.IO.File.ReadAllText(path);
if (existsCode != code)
{
System.IO.File.WriteAllText(path, code);
}
}
#region 构造代码
public static string CreateCode(List<DtoClass> dtos)
{
StringBuilder code = new StringBuilder();
foreach (var dto in dtos)
{
code.AppendLine($"/** {dto.Title} {dto.Namespace}*/");
code.AppendLine($"export interface {dto.Name} {
{");
foreach (var property in dto.Propertys)
{
if (property.IsInverseProperty) continue;
string comment = $" /** <Title><Dept> */";
comment = comment.Replace("<Title>", property.Title ?? "");
if (property.IsKey)
comment = comment.Replace("<Dept>", $"\r\n @Key<Dept>");
if (property

本文介绍了一个利用C#编写的代码生成工具,该工具能够自动生成Angular项目中所需的TypeScript接口代码,根据C#的DTO类。通过反射获取程序集中的DTO类信息,然后生成对应的TS代码,减少了手动转换的繁琐工作,提高了前后端开发效率,并能及时发现后端DTO变更的问题。
最低0.47元/天 解锁文章
759

被折叠的 条评论
为什么被折叠?



