C# CodeDOM:在运行时添加 Enum 成员
我想做的是将“NoneOfTheBelow”选项添加到从 XSD 文件解析的所有枚举中。 我正在扩展 Xsd2Code 工具 中的代码。
当我使用下面的代码生成输出时,枚举不包含我添加的新成员。 有人可以帮忙吗?
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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于枚举,您需要添加 CodeMemberField 实例,而不是 CodeTypeMember,因此类似于:
For enumerations, you need to add CodeMemberField instances, not CodeTypeMember, so something like: