简体   繁体   中英

How to create a constructor with a parameter with Roslyn?

I'm generating classes from an Open API specification and need to create a constructor that accepts a parameter and sets it to a field. How do I do that with Roslyn?

I ended up using this code to create a constructor that accepts a parameter and sets it to a field:

SyntaxFactory.ConstructorDeclaration("MyClass")
    .AddParameterListParameters(
        SyntaxFactory.Parameter(SyntaxFactory.Identifier("myParameter"))
            .WithType(SyntaxFactory.ParseTypeName("string")))
    .WithBody(SyntaxFactory.Block(SyntaxFactory.ParseStatement($"_myField = myParameter;")))
    .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));

The generated constructor for this code is:

public MyClass(string myParameter)
{
     _myField = myParameter;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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