首页 > 代码库 > 提取c#代码文件中的方法块
提取c#代码文件中的方法块
此方法是取C#文件里面的方法块,并删除缩进符,感觉写得还是比较容易懂的,所以收藏下,以便将来用到.
private static string GetCodeBlock(string allCode, string blockName) { int blockStart = allCode.IndexOf(blockName, StringComparison.OrdinalIgnoreCase); if (blockStart == -1) return "// " + blockName + " code not found"; blockStart = allCode.LastIndexOf(Environment.NewLine, blockStart, StringComparison.OrdinalIgnoreCase); if (blockStart == -1) blockStart = 0; else blockStart += Environment.NewLine.Length; int pos = blockStart; int braceCount = 0; char c; do { pos++; c = allCode[pos]; switch (c) { case ‘{‘: braceCount++; break; case ‘}‘: braceCount--; break; } } while (pos < allCode.Length && !(c == ‘}‘ && braceCount == 0)); int blockEnd = pos; string blockCode = allCode.Substring(blockStart, blockEnd - blockStart + 1); return removeIndent(blockCode); } private static string RemoveIndent(string code) { int indentSpaces = 0; while (code[indentSpaces] == ‘ ‘) { indentSpaces++; } StringBuilder builder = new StringBuilder(); string[] codeLines = code.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); foreach (string line in codeLines) { if (indentSpaces < line.Length) builder.AppendLine(line.Substring(indentSpaces)); else builder.AppendLine(); } return builder.ToString(); }
提取c#代码文件中的方法块
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。