使用.NET的codeDOM创建枚举 [英] creating enumeration using .NET's CodeDom
问题描述
我想用 codeDOM API
来创建一个枚举。我寻觅足够在互联网上,我得到的结果,它们是任何使用几乎没有。
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.
我要生成的
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
属性为真,也创造了一个名称,并设置它的属性。
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?
我试过
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);
虽然使用这个解决方案,我可以生成描述属性,线的末端将是;
,而不是,
推荐答案
枚举成员的领域,所以使用codeMemberField:
Enum members are fields, so use CodeMemberField:
CodeTypeDeclaration type = new CodeTypeDeclaration("BugTracker");
type.IsEnum = true;
foreach (var valueName in new string[] { "Bugzilla", "Redmine" })
{
// Creates the enum member
CodeMemberField f = new CodeMemberField("BugTracker", valueName);
// Adds the description attribute
f.CustomAttributes.Add(new CodeAttributeDeclaration("Description", new CodeAttributeArgument(new CodePrimitiveExpression(valueName))));
type.Members.Add(f);
}
(在这个简化的code,该说明将永远是一样的会员名称。当然,在你真正的code,这些可以是不同的。)
(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.)
一个小怪癖,你可能会注意到的是,codeDOM最后一个枚举值后加一个逗号:
A little quirk you may notice is that CodeDom adds a comma after the last enum value:
public enum BugTracker {
[Description("Bugzilla")]
Bugzilla,
[Description("Redmine")]
Redmine, // trailing comma
}
这是由C#语言,$ P $允许pcisely以支持generated- code的情况就是这样,和将编译罚款,即使它看上去有些奇怪,以人类的阅读器。
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.
这篇关于使用.NET的codeDOM创建枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!