Roslyn+T4+EnvDTE项目完全自动化(4) ——批量生成参数检查


(视频演示)

类似功能写了几十个,基本上只要项目中重复两次以上,都可以用Roslyn自动化实现

需求:批量生成参数查方法

  1. 对类自动生成参数检查代码
  2. 对ef类自动识别非空字段,Unicode字段,成参数检查代码
  3. 自动翻译字段
    public partial class film
    {
        public void CheckFields()
        {
            if (title == null)
            {
                throw new Exception("标题 不能为空!");
            }
            if (title != null)
            {
                var length = System.Text.Encoding.UTF8.GetByteCount(title);
                const int max = 255;
                if (length > max)
                {
                    throw new Exception($"标题 长度 {length} 不能超过 {max}!");
                }
            }
            if (description != null)
            {
                var length = System.Text.Encoding.UTF8.GetByteCount(description);
                const int max = 65535;
                if (length > max)
                {
                    throw new Exception($"描述 长度 {length} 不能超过 {max}!");
                }
            }
            if (rating != null)
            {
                var length = System.Text.Encoding.UTF8.GetByteCount(rating);
                const int max = 65532;
                if (length > max)
                {
                    throw new Exception($"评级 长度 {length} 不能超过 {max}!");
                }
            }
            if (special_features != null)
            {
                var length = System.Text.Encoding.UTF8.GetByteCount(special_features);
                const int max = 65531;
                if (length > max)
                {
                    throw new Exception($"特色 长度 {length} 不能超过 {max}!");
                }
            }
        }
    }