创建使用Roslyn的FxCop自定义代码分析规则的最佳方法是什么?

时间:2015-07-03 11:03:35

标签: c# .net code-analysis roslyn fxcop

我的任务是创建一个可以捕获吞噬异常的代码分析规则。一切都运行良好,直到我使用异步方法测试我的规则,并且规则无法检测吞下的异常。

我决定试试罗斯林。为了让Roslyn工作,我需要知道源文件的位置,并且我能够从属性member.SourceContext.FileName获得它。问题是,这个属性并不总是存在。我注意到非公开方法总是如此。

是否有可靠的方法使用FxCode代码分析引擎获取源文件?有没有更好的方法来使用roslyn进行代码分析?

FxCop规则:

internal sealed class DoNotSwallowExceptionsRule : BaseFxCopRule
{
    public override ProblemCollection Check(Member member)
    {
         Method method = member as Method;
         if (method != null && method.Body != null && method.Instructions != null)
         {
             string sourcefileName = method.SourceContext.FileName; //sometimes is null

             if (sourcefileName != null)
             {
                string source = File.ReadAllText(sourcefileName);

                var result = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(source);
             }
         }
         return Problems;
    }
}

0 个答案:

没有答案