c# - Using Roslyn to parse/transform/generate code: am I aiming too high, or too low? -
(what i'm trying work around application.settings/mvvm problem generating interface , wrapper class vs-generated settings file.)
what i'd is:
- parse class declaration file
- generate interface declaration based on (non static) properties of class
- generate wrapper class implements interface, takes instance of original class in constructor, , 'pipes' properties through instance.
- generate class implements interface directly.
my question two-fold:
- am barking wrong tree? better off using code-dom, t4, regex(!) this, or part of this? (i don't mind bit of work, learning experience.)
- if roslyn way go, bit of should looking at? kind of naively hoping there way of walking tree , spitting out bits want, i'm having trouble getting head round whether/how use syntaxrewriter it, or whether use fluent-style construction, querying source multiple times bits need.
if want comment on mvvm aspect can, that's not main thrust of question :)
if requirement parsing c# source code, think roslyn choice. , if you're going use part, think makes sense use code generations.
code generation using roslyn can quite verbose (especially when compared codedom), think that's not going big issue you.
i think syntaxrewriter
best suited making localized changes in code. you're asking parsing whole class , generating types based on that, think that, querying syntax tree directly work best.
for example, simplest example of generating read-only interface properties in class this:
var originalclass = compilationunit.descendantnodes().oftype<classdeclarationsyntax>().single(); string originalclassname = originalclass.identifier.valuetext; var properties = originalclass.descendantnodes().oftype<propertydeclarationsyntax>(); var generatedinterface = syntaxfactory.interfacedeclaration('i' + originalclassname) .addmembers( properties.select( p => syntaxfactory.propertydeclaration(p.type, p.identifier) .addaccessorlistaccessors( syntaxfactory.accessordeclaration(syntaxkind.getaccessordeclaration) .withsemicolontoken(syntaxfactory.token(syntaxkind.semicolontoken)))) .toarray());
Comments
Post a Comment