C#CodeDOM:在运行时添加Enum成员

时间:2011-02-21 19:56:47

标签: c# codedom

我要做的是为从XSD文件解析的所有枚举添加“NoneOfTheBelow”选项。 我正在扩展Xsd2Code tool的代码。

当我使用下面的代码生成输出时,枚举不包含我添加的新成员。 有人可以帮忙吗?

var ns = new CodeNamespace();

/* ... Initialize ns from XSD ... */

// Create a dummy array for iteration, because a collection cannot be modified when it is being iterated over.
CodeTypeDeclarationCollection types = new CodeTypeDeclarationCollection();
foreach (CodeTypeDeclaration t0 in ns.Types)
{
   types.Add(new CodeTypeDeclaration(t0.Name));
}

// Scan for enum types and add desired markup to the members.
int typeIndex = 0;
foreach (CodeTypeDeclaration t0 in types)
{
   CodeTypeDeclaration t = ns.Types[typeIndex];

   // Add an element for blank entry to the enum.
   CodeTypeMember noneOfTheBelow = new CodeTypeMember();
   noneOfTheBelow.Name = "NoneOfTheBelow";
   noneOfTheBelow.Comments.Add(new CodeCommentStatement( "<summary>None of the below.</summary>"));
   noneOfTheBelow.CustomAttributes.Add(new CodeAttributeDeclaration("XmlEnum", new CodeAttributeArgument(new CodePrimitiveExpression("Test"))));
   noneOfTheBelow.CustomAttributes.Add(new CodeAttributeDeclaration("Description", new CodeAttributeArgument(new CodePrimitiveExpression("Test"))));
   t.Members.Insert(0, noneOfTheBelow);
}

1 个答案:

答案 0 :(得分:0)

对于枚举,您需要添加CodeMemberField实例,而不是CodeTypeMember,如下所示:

CodeMemberField noneOfTheBelow = new CodeMemberField();
noneOfTheBelow.Attributes = MemberAttributes.Public | MemberAttributes.Static;
noneOfTheBelow.Name = "NoneOfTheBelow";
t.Members.Insert(0, noneOfTheBelow);