简体   繁体   English

如何使用Roslyn正确修改类声明语法?

[英]How do I modify class declaration syntax correctly with Roslyn?

I have a method below to modify class declaration syntax. 我下面有一种方法可以修改类声明语法。 I added two StatementSyntax attributes to all methods in the class, and then I will save that class to my solution. 我向该类中的所有方法添加了两个StatementSyntax属性,然后将该类保存到解决方案中。 Everything is good, but the method ReplaceNode only works for the first method, ListOfMethod . 一切都很好,但是方法ReplaceNode仅适用于第一个方法ListOfMethod Which part of my method is incorrect? 我的方法的哪一部分不正确?

private ClassDeclarationSyntax GetNewClass(ClassDeclarationSyntax c)
{
    List<MethodDeclarationSyntax>  ListOfMethod = lom(c);
    foreach (var OldMethod in ListOfMethod )
    {
        MethodDeclarationSyntax NewMethod = GetNewMethod (OldMethod);
        c = c.ReplaceNode(OldMethod,NewMethod);
    }
    return c;
}

In Roslyn, most of the data structures are immutable, so when you call a modifying method on something, then that operation will return a new modified object, and not perform the modification in place. 在Roslyn中,大多数数据结构都是不可变的,因此,当您对某物调用修改方法时,该操作将返回一个新的修改后的对象,而不是就地执行修改。

So in your case, you collect all the methods that interest you from a given ClassDeclarationSyntax . 因此,在您的情况下,您将从给定的ClassDeclarationSyntax收集所有您感兴趣的方法。 When you call the ReplaceNode , that returns a new class declaration. 当您调用ReplaceNode ,它将返回一个新的类声明。 This new class declaration won't contain any of your previously found methods, because it's a new class declaration instance. 这个新的类声明不会包含您以前找到的任何方法,因为它是一个新的类声明实例。

One option is to do the change in a single call with ReplaceNodes , and in your case this seems to be the approach to follow. 一种选择是使用ReplaceNodes在单个调用中进行ReplaceNodes ,在您的情况下,这似乎是遵循的方法。

Another option is to try to mark the methods with some permanent marking that is not lost during tree modification. 另一个选择是尝试使用一些永久性标记来标记方法,这些永久性标记在树修改期间不会丢失。 To do this you can add annotations to the nodes with WithAdditionalAnnotations() , and then you can find in the tree a given node with a given annotation. 为此,您可以使用WithAdditionalAnnotations()将注释添加到节点,然后在树中找到具有给定注释的给定节点。

I changed the method like below .every time I use the method ReplaceNode the new classdeclarationsyntax will be created then I must get next MethodDeclarationSyntax from this new one 我更改了如下方法。每次使用方法ReplaceNode时,都会创建新的classdeclarationsSyntax,然后必须从这个新的类中获取下一个MethodDeclarationSyntax

into Count =c.Members.OfType <MethodDeclarationSyntax>().Count();
for  (int i=0;i <Count; i++)
{
    List <MethodDeclarationSyntax > l=c.Members.OfType <MethodDeclarationSyntax>().ToList();
    MethodDeclarationSyntax NewMethod=GetNewMethod (l [i]);
    c=c.ReplaceNode(l [i],NewMethod);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM