Đang cố gắng với một chẩn đoán và một CodeFix để làm cho một mã số người chuyển đổi rằng:Roslyn C# incrementing thay đổi
variable = variable + 1;
otherVariable = otherVariable -1;
Into:
variable++;
otherVariable--;
Đã thực hiện các chẩn đoán (nó hoạt động):
var incrementing = node as BinaryExpressionSyntax;
if (incrementing != null)
{
string right = incrementing .Right.ToString();
string left = incrementing .Left.ToString();
if (right == left + " - 1" || right == left + " + 1")
{
addDiagnostic(Diagnostic.Create(Rule, incrementation.GetLocation(), "Use the shorter way"));
}
}
Chỉnh sửa: Tôi đã thực hiện một số thay đổi. Bây giờ, việc tăng dần luôn được nhận ra. Chương trình đi trong CodeFix, nhưng ReplaceToken của tôi với SyntaxFactory không hoạt động. (Nó bây giờ chỉ dành cho "++" chứ không phải "-"):
if (node.IsKind(SyntaxKind.SimpleAssignmentExpression)) //I use a node instead of a token
{
var IncrementationClause = (BinaryExpressionSyntax)node;
string left = IncrementationClause.Left.ToString();
left = left + "++";
string rigt = IncrementationClause.Right.ToString();
var newIncrementationClause = IncrementationClause.ReplaceToken(SyntaxFactory.Identifier(IncrementationClause.Left.ToString()), SyntaxFactory.Identifier(left));
newIncrementationClause = IncrementationClause.ReplaceToken(SyntaxFactory.Identifier(IncrementationClause.Right.ToString()), SyntaxFactory.Identifier(String.Empty));
newIncrementationClause = IncrementationClause.ReplaceToken(SyntaxFactory.Identifier(IncrementationClause.OperatorToken.ToString()), SyntaxFactory.Identifier(String.Empty));
var newRoot = root.ReplaceNode(IncrementationClause, newIncrementationClause);
return new[] { CodeAction.Create("Changer la mise en forme", document.WithSyntaxRoot(newRoot)) };
}
Bạn nên phân tích các cây cú pháp, không kiểm tra các đại diện chuỗi. 'ToString()' có thể không trả lại những gì bạn mong đợi. – SLaks
Tôi đã tìm đường và bây giờ nó đi trong CodeFix. Nhưng không có gì thay đổi ... Tôi có một CodeAction, nhưng không có hành động nào được thực hiện. Khi tôi gỡ lỗi từng bước, tôi có thể thấy rằng newIncrementationClause chính xác giống như IncrementationClause. Có lẽ bạn có thể giúp tôi :) – Maloz
Bạn đang thay thế một nút mới mà bạn vừa tạo, theo định nghĩa không có trong cây. Bạn không bao giờ nên làm việc với 'node.ToString()'; luôn sử dụng các API Node trực tiếp. – SLaks