前端也要后端的DTO咋办,代码生成走一波。

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

姐妹篇《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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值