Roslyn 如何使用多个声明修饰符创建 class

Roslyn how to create a class with multiple Declaration Modifiers

我正在创建一个代码生成器。为了简化我遇到的问题,如何生成具有多个声明修饰符的 class?

class生成器只有一个构造函数用于添加单个声明修饰符

this._syntaxGenerator = SyntaxGenerator.GetGenerator(workspace, LanguageNames.CSharp);
var classNode = this._syntaxGenerator.ClassDeclaration(classOptions.Name, null, 
                      classOptions.InternalAccessModifier, DeclarationModifiers.Sealed)
                     .NormalizeWhitespace();

假设我想创建一个密封的部分 class 或带有多个声明修饰符的东西,我该怎么做?

只需尝试使用一些现有的修饰符并使用 WithIs** 重新创建一个新的修饰符。它看起来像这样:

var modifiers = DeclarationModifiers.Sealed.WithIsAbstract(true).WithIsStatic(true);

之后只需要传入SyntaxGenerator.ClassDeclaration

您可以使用“|”用于组合声明修饰符的运算符:

DeclarationModifiers.Sealed | DeclarationModifiers.Abstract

就像标志枚举一样。