0

我正在尝试使用 NRefactory 来修改现有的一段 C# 代码。我已经尝试使用本文中描述的方法。我收到一个抱怨重复更改的异常。有人可以指出我做错了什么,并指出我正确的方向吗?

我有以下代码部分:

// contains the source code that needs to be modified
var text = "...";
// is the name of the file in which the target class exists
var fileName = "Foo";
// is the name of the target class
var className = "Foo.cs"; 

// FormattingOptions and TextEditorOptions are properties available to
// the class containing this code...

var parser = new CSharpParser();

var syntaxTree = parser.Parse(text, fileName);

syntaxTree.Freeze();

var document = new StringBuilderDocument();

document.Text = syntaxTree.ToString(FormattingOptions);

using (var documentScript = new DocumentScript(document, FormattingOptions, TextEditorOptions))
{
    var typeDeclarations = syntaxTree.Descendants.OfType<TypeDeclaration>().Where(typeDeclaration => typeDeclaration.Name == className);
    var templateProviderDeclaration = typeDeclarations.SingleOrDefault();

    if (templateProviderDeclaration != null)
    {
        var constructorDeclarations = templateProviderDeclaration.Descendants.OfType<ConstructorDeclaration>();

        foreach (var constructorDeclaration in constructorDeclarations)
        {
            var assignmentExpressions = constructorDeclaration.Descendants.OfType<AssignmentExpression>();

            foreach (var assignmentExpression in assignmentExpressions)
            {
                var leftExpression = assignmentExpression.Left;

                if (leftExpression != null && leftExpression.ToString(FormattingOptions) == "this.templates")
                {
                    var rightExpression = assignmentExpression.Right;

                    foreach (var arrayInitializerExpression in rightExpression.Children.OfType<ArrayInitializerExpression>())
                    {
                        // uses AddTemplate(), which is an extension method
                        // which takes in an expression and modifies it, and
                        // returns an expression
                        var newExpression = ((ArrayInitializerExpression)arrayInitializerExpression).AddTemplate();

                        documentScript.Replace(arrayInitializerExpression, newExpression);
                    }
                }
            }
        }
    }

    // text retrieved here is *clobbered*, by a few characters
    text = documentScript.CurrentDocument.Text;
}

其他代码...

public static class ExtensionMethods
{
    public static ArrayInitializerExpression AddTemplate(this ArrayInitializerExpression expression)
    {
        // TODO : will modify the AST for the target expression

        return (ArrayInitializerExpression)expression.Clone();
    }
}

更新:

我正在尝试更改这样的一行:

this.templates = new Dictionary<string, ITemplate>
{
    { "Foo", new FooTemplate() }
};

至:

this.templates = new Dictionary<string, ITemplate>
{
    { "Foo", new FooTemplate() },
    { "Bar", new BarTemplate() }
};

就这个问题而言,我试图做出的改变的具体细节并不重要。我怀疑我的某些东西构造不正确,但我不知道这是否是问题所在。

4

0 回答 0