拼接枚举字符串

我们需要自定义规则,然后进行拼接字符串

       //枚举定义规则: xxxm枚举(value.key[Des];) 
            // 枚举结尾,()中是枚举定义,[]中是描述值可有可无, .分割值和key,  ;分割每个定义
            string enumString = "测试枚举(7.Sunday[星期天];1.Monday[星期一];2.Tuesday[星期二];3.Wednesday[];5.Friday)";
            string math = Regex.Match(enumString, @"(?<=枚举).*").Value; //得到枚举字符串,带()
            string text = math.Replace("(", "").Replace(")", ""); //去除()
            string one = "    ";  //一级空格
            string two = "        "; //二级空格
            StringBuilder enumSb = new StringBuilder();
            //拼接头部
            enumSb.AppendLine($"{one}/// <summary>");
            enumSb.AppendLine($"{one}/// 测试枚举");
            enumSb.AppendLine($"{one}/// </summary>");
            enumSb.AppendLine($"{one}public enum TestEnum");
            enumSb.AppendLine($"{one}{{");   
            int i = 1;
            string[] arry = text.Split(';');
            foreach (string item in arry)
            {
                if (item.Contains("[")&&item.Contains("]"))  //是否包含描述
                {
                    string[] arry3 = item.Split('['); 
                    string[] arry2 = arry3[0].Split('.');
                    //拼接枚举值
                    enumSb.AppendLine($"{two}/// <summary>");
                    enumSb.AppendLine($"{two}/// {arry2[1]}");
                    enumSb.AppendLine($"{two}/// </summary>");
                    enumSb.AppendLine($"{two}[Description("{arry3[1].Replace("]","")}")]");
                    if (i == arry.Length)  //最后一个不带,
                    {
                        enumSb.AppendLine($"{two}{arry2[1]} = {arry2[0]}");
                    }
                    else   //带,
                    {
                        enumSb.AppendLine($"{two}{arry2[1]} = {arry2[0]},");
                    }
                    enumSb.AppendLine("");

                }
                else
                {
                    string[] arry2 = item.Split('.');
                    enumSb.AppendLine($"{two}/// <summary>");
                    enumSb.AppendLine($"{two}/// {arry2[1]}");
                    enumSb.AppendLine($"{two}/// </summary>");
                    if (i == arry.Length)
                    {
                        enumSb.AppendLine($"{two}{arry2[1]} = {arry2[0]}");
                    }
                    else
                    {
                        enumSb.AppendLine($"{two}{arry2[1]} = {arry2[0]},");
                    }
                    enumSb.AppendLine("");
                }
               
                i++;
            }
            enumSb.AppendLine($"{one}}}");

原文地址:https://www.cnblogs.com/Sea1ee/p/10334963.html