使用Roslyn向类添加新的字段声明

时间:2017-07-18 07:55:24

标签: c# roslyn roslyn-code-analysis

有一些方法可以使用roslyn将成员添加到类中吗?我想补充一下:

public int number {get;set;}

UPDATE 我用了这段代码:

       PropertyDeclarationSyntax o =  
       SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName("public  
       System.Windows.Forms.Timer"), "Ticker { get; set; }");

       var newRoot = root.ReplaceNode(oldMethod, oldMethod.AddMembers(o));
       newRoot = Formatter.Format(newRoot, new AdhocWorkspace());

       File.WriteAllText(file, newRoot.ToFullString());

但结果如下:

   public class ClassChild
{
    public int n;
    private int n2;

    public void method1()
    {
        string c = "";
        Console.WriteLine();
    }

public System.Windows.Forms.TimerTicker { get; set; }
}

}

我想内联公共System.Windows.Forms.TimerTicker {get;组;与n和n2。我该怎么做?

2 个答案:

答案 0 :(得分:3)

参见代码

    private PropertyDeclarationSyntax MakeProperty()
    {
        string name = "n";

        // Create an auto-property
        var property =
            SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName("int"), name)
            .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
            .AddAccessorListAccessors(
                SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
            );

        return property;
    }

    private async Task<Document> AddProperty(Document document, ClassDeclarationSyntax classeDecl, CancellationToken cancellationToken)
    {
        var root = await document.GetSyntaxRootAsync(cancellationToken);
        var newClass = classeDecl.AddMembers(MakeProperty());
        return document.WithSyntaxRoot(root.ReplaceNode(classeDecl, newClass));
    }

自动属性生成示例取自this问题。

答案 1 :(得分:0)

我个人更喜欢这种技术:

public static class SyntaxHelpers
{
    public static T GenerateClassNode<T>(string decl) where T : CSharpSyntaxNode
    {
        var declaration = SyntaxFactory.ParseCompilationUnit(
            " public class FSM { \r\n" +
            $"{decl}\r\n" +
            " }} \r\n");

        var field = declaration.Members[0].DescendantNodes().First() as T;
        return field;
    }
}

然后您可以按以下方式使用它:

string log4NetLoggerDeclaration =
                    "private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);";

var log4NetDeclarationStatement = SyntaxHelpers.GenerateClassNode<FieldDeclarationSyntax>(log4NetLoggerDeclaration);

string declarationString = log4NetLoggerDeclaration.ToString();