There is some way to add a member to a class with roslyn? I want to add :
public int number {get;set;}
UPDATE I used this code:
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());
But the the result is this:
public class ClassChild
{
public int n;
private int n2;
public void method1()
{
string c = "";
Console.WriteLine();
}
public System.Windows.Forms.TimerTicker { get; set; }
}
}
I would like to inline public System.Windows.Forms.TimerTicker { get; set; } with n and n2. How Can I do this ?
See the code
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));
}
Auto property genaration example is taken from this question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With