有时候,我们可能需要获取.cs文件中的属性和对应的注释来生成一些代码,比如SQL查询什么的。
但使用正则匹配有时候会不准确。搜索了下,发现微软提供了代码解析的API。
具体如下两个方法:
/// <summary>
/// 获取所有属性和对应的文档注释
/// </summary>
/// <param name="codeContent"></param>
/// <returns></returns>
private Dictionary<string, string> GetPropertyAndItsComment(string codeContent)
{
Dictionary<string, string> result= new Dictionary<string, string>();
SyntaxTree tree = CSharpSyntaxTree.ParseText(codeContent);
CompilationUnitSyntax root = tree.GetCompilationUnitRoot();
var classDec = (NamespaceDeclarationSyntax)root.Members[0];
var programDeclaration = (ClassDeclarationSyntax)classDec.Members[0];
foreach (MemberDeclarationSyntax mem in programDeclaration.Members)
{
if (mem is PropertyDeclarationSyntax)
{
PropertyDeclarationSyntax pro = (PropertyDeclarationSyntax)mem;
result.Add(pro.Identifier.Text, GetDocComment(mem));
}
}
return result;
}
/// <summary>
/// 获取注释内容并做处理
/// </summary>
/// <param name="pro"></param>
/// <returns></returns>
private string GetDocComment(MemberDeclarationSyntax pro)
{
foreach (SyntaxTrivia trivia in pro.GetLeadingTrivia())
{
if (trivia.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia)
|| trivia.IsKind(SyntaxKind.MultiLineDocumentationCommentTrivia)
)
{
string conmment = trivia.ToString().Replace("///","");
conmment = conmment.Replace("<summary>", "");
conmment = conmment.Replace("</summary>", "");
conmment = conmment.Trim();
return conmment;
}
}
return "";
}