使用 .NET 的 CodeDom 创建枚举
我想使用 CodeDom API
创建一个枚举。我在互联网上进行了足够的搜索,但得到的结果几乎没有任何用处。
我想要生成的是
public enum bug_tracker_type
{
[Description("Bugzilla")]
Bugzilla,
[Description("Debbugs")]
Debbugs,
[Description("PHP Project Bugtracker")]
PHP_Project_Bugtracker,
[Description("Google Code")]
Google_Code
}
我使用了 CodeTypeDeclaration 并将其 IsEnum 属性设置为 true,创建了一个名称并设置了它的属性。
现在最大的问题是如何填充身体?
我尝试过
CodeTypeMember mem = new CodeTypeMember();
mem.Name = WadlSharpUtils.CreateIdentifier(discreteValue.value);
mem.CustomAttributes.Add(new CodeAttributeDeclaration(discreteValue.value));
// enumCandidate is an instance of CodeTypeDeclaration
enumCandidate.Members.Add(mem);
虽然使用这个解决方案我可以生成描述属性,但行尾将是 ;
而不是 ,
I want to create an Enumeration using CodeDom API
. I have searched enough on the internet and I get results which are hardly of any use.
What I want to generate is
public enum bug_tracker_type
{
[Description("Bugzilla")]
Bugzilla,
[Description("Debbugs")]
Debbugs,
[Description("PHP Project Bugtracker")]
PHP_Project_Bugtracker,
[Description("Google Code")]
Google_Code
}
I used CodeTypeDeclaration
and set it's IsEnum
property as true, created a name, and set it's Attributes.
Now the biggest problem is how to populate the body?
I tried
CodeTypeMember mem = new CodeTypeMember();
mem.Name = WadlSharpUtils.CreateIdentifier(discreteValue.value);
mem.CustomAttributes.Add(new CodeAttributeDeclaration(discreteValue.value));
// enumCandidate is an instance of CodeTypeDeclaration
enumCandidate.Members.Add(mem);
Though using this solution I can generate the Description attributes, the end of line would be ;
and not ,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
枚举成员是字段,因此使用 CodeMemberField:(
在这个简化的代码中,描述将始终与成员名称相同。当然,在您的真实代码中,这些可以不同。)
您可能会注意到的一个小怪癖是 CodeDom在最后一个枚举值后添加一个逗号:
这是 C# 语言允许的,正是为了支持这样的生成代码场景,并且即使对人类读者来说看起来有点奇怪,也能很好地编译。
Enum members are fields, so use CodeMemberField:
(In this simplified code, the Description will always be the same as the member name. In your real code, of course, these can be different.)
A little quirk you may notice is that CodeDom adds a comma after the last enum value:
This is permitted by the C# language, precisely in order to support generated-code scenarios like this, and will compile fine even if it looks a bit odd to the human reader.