使用Roslyn的方法的参数验证

时间:2019-07-24 06:19:08

标签: c# roslyn roslyn-code-analysis

我想在编译时为扩展方法执行参数验证。

类似这样的东西

enter image description here

这是我要验证的程序的示例代码

public class Program
{
    static void Main(string[] args)
    {
        var sample = new Sample();
        var output = sample.SampleMethod("To Validate");  // I want to validate this param
    }
}

public static class Ext
{
    public static string SampleMethod(this Sample sample, string sampleParam)
    {
        return sampleParam + " Hello";
    }
}

public class Sample
{

}

我打算使用Roslyn,但我不知道Action进行注册并获取传递的参数值。

使用Roslyn验证方法参数的示例代码将非常有帮助

1 个答案:

答案 0 :(得分:0)

您可以使用https://sharplab.io/查看代码的语法树。

您可能想注册一个操作而不是一个操作:

context.RegisterOperationAction(YourAnalyzer, OperationKind.Invocation);

您可以在这些存储库中找到许多示例:

  1. https://github.com/dotnet/roslyn-analyzers
  2. https://github.com/DotNetAnalyzers/StyleCopAnalyzers
  3. https://github.com/code-cracker/code-cracker