简体   繁体   中英

C# CodeDOM: Adding Enum members at runtime

What I'm trying to do is add a "NoneOfTheBelow" choice to all enums parsed from an XSD file. I'm expanding on code from the Xsd2Code tool .

When I generate output using the code below, the enum does not contain the new member I added. Can anyone help?

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);
}

For enumerations, you need to add CodeMemberField instances, not CodeTypeMember, so something like:

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

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