[英]Roslyn Analyzer for String comparison
我想編寫一個用於字符串比較的 roslyn 分析器。 這些情況是: s1 可以是一個字符串。 所以如果 s1.equals(s2) 或 s1 == s2; 它應該修復為 string.equals(s1,s2,Stringcomparsion.Ordinal)
我對樹有了基本的了解,還需要創建一個分析器文件和一個 CodeFixProvider class。
所以我試圖獲取例如語法樹。 s1.等於(s2)。
現在為了編寫分析代碼方法,我不知道如何驗證 s1 是否為字符串。 所以我在這里需要幫助。
我正在嘗試關注這篇文章https://www.meziantou.net/writing-a-roslyn-analyzer.htm 。
例如。
Class{
string s1 = "one";
string s2 = "two";
bool res = one.equals(two);
}
應該重構為:
Class{
string s1 = "one";
string s2 = "two";
bool res = string.equals(one,two, StringComparsion.Ordinal);
}
您可以查看規則 MA0006 的執行情況: GitHub
您還可以查看我關於其他字符串分析器的字符串比較的帖子: https://www.meziantou.net/string-comparisons-are-harder-than-it-seems.htm#getting-warnings-in
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class UseStringEqualsAnalyzer : DiagnosticAnalyzer
{
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterOperationAction(AnalyzeInvocation, OperationKind.BinaryOperator);
}
private static void AnalyzeInvocation(OperationAnalysisContext context)
{
var operation = (IBinaryOperation)context.Operation;
if (operation.OperatorKind == BinaryOperatorKind.Equals ||
operation.OperatorKind == BinaryOperatorKind.NotEquals)
{
if (operation.LeftOperand.Type.IsString() && operation.RightOperand.Type.IsString())
{
if (IsNull(operation.LeftOperand) || IsNull(operation.RightOperand))
return;
// EntityFramework Core doesn't support StringComparison and evaluates everything client side...
// https://github.com/aspnet/EntityFrameworkCore/issues/1222
if (operation.IsInExpressionArgument())
return;
context.ReportDiagnostic(s_rule, operation, $"{operation.OperatorKind} operator");
}
}
}
private static bool IsNull(IOperation operation)
{
return operation.ConstantValue.HasValue && operation.ConstantValue.Value == null;
}
}
請注意,如果您只是希望讓此分析器在您自己的代碼上運行並且對實際編寫它不太感興趣,那么這已經在 Microsoft 編寫的分析器中實現:
https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1307
安裝說明可在此處獲得:
https://github.com/dotnet/roslyn-analyzers#microsoftcodeanalysisfxcopanalyzers
我們的代碼也可用,但如果您確實希望簡單的代碼開始理解分析器,@meziantou 的回答就是一個很好的例子。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.