2014-10-20 39 views
1

我正試圖爲集合初始化程序及其相應的代碼修復提供程序實現診斷分析程序。不能專門遍歷語法樹嗎?

錯誤代碼:

var sampleList= new List<string>(); 
sampleList.Add(""); 
sampleList.Add(""); 

CodeFix後:

var sampleList= new List<string>(){"", ""}; 

但我堅持這個問題,一旦我得到LocalDeclarationStatement一個節點,我不知道,如果存在一個從父節點獲取下一個相鄰節點的方法。

Syntax Tree

在上面的圖片我需要兩個ExpressionStatement分析LocalDeclarationStatement

要求爲了分析

  1. 識別LocalDeclarationStatement,一個已經初始化的集合之後,但犯規包含CollectionInitializerExpression
  2. 查找下一行是否有表達式聲明是usin摹Add方法在同一採集

需要量爲代碼修復

  1. 對於使用Add方法對收集
  2. Add方法的所有其他間斷的使用相鄰的表達式語句提供集合初始化語法在收集上必須避免。

回答

3

你可以這樣做:

var declarationStatement = ...; 
var block = (BlockSyntax)declarationStatement.Parent; 
var index = block.Statements.IndexOf(declarationStatement); 
var nextStatement = block.Statements[index + 1]; 
+0

這工作完全正常!我真的很感激。 – 2014-10-21 05:08:44

+0

我們如何刪除使用相同的CodeFix提供程序替換爲集合初始值設定項語法的附加代碼行(相鄰的'Add'調用)。我能夠爲集合初始化器提供修復,但無法刪除其他連續的「添加」調用行。 – 2014-10-21 12:35:11

+0

@JerricLynsJohn你嘗試過'RemoveNode'擴展方法嗎? – svick 2014-10-21 15:15:54

1

難道你只是需要把混凝土塊變成列表,並檢查?

var nodes = yourSyntaxTree.DescentNodes().ToList(); 

for(var i = 0; i < nodes.Count; i++){ 
    var localDeclarationStatement = nodes[i] as LocalDeclarationStatement; 
    if(localDeclarationStatement==null && i + 1 >= nodes.Length) 
     continue; 

    var expressionStatement = nodes[i+1] as ExpressionStatement; 
    if(expressionStatement==null) 
    continue; 

    // there you have it. 
}