我使用枚举类型数据类型在windows形式的c#中的comboBox中添加字符串元素,但是在添加元素时出现了错误。 错误是(“标识符预期”) 我的代码是
public enum EducationG
{
("Bachelor of Arts (B.A)"),
("Bachelor of Arts (Bachelor of Education (B.A. B.Ed)")],
("Bachelor of Arts (Bachelor of Law (B.A.B.L)"),
("Bachelor of Arts (Bachelor of Law (B.A.LLB)"),
("Bachelor of Ayurvedic Medicine and Surgery (B.A.M.S)"),
("Bachelor of Applied Sciences (B.A.S)"),
("Bachelor of Audiology and Speech Language Pathology (B.A.S.L.P)"),
("Bachelor of Architecture (B.Arch)"),
("Bachelor of Business Administration (B.B.A)"),
("Bachelor of Business Administration (Bachelor of Law (B.B.A LL.B)"),
("Bachelor of Business Management (B.B.M)"),
("Bachelor of Business Studies (B.B.S)"),
("Bachelor of Computer Applications (B.C.A)"),
("Bachelor of Communication Journalism (B.C.J)"),
("Bachelor of Computer Science (B.C.S)")
}
答案 0 :(得分:1)
你做不到,但你可以这样做:
public enum EducationG
{
[Description("Bachelor of Arts (B.A)")]
BachelorOfArtsBA,
...
}
您可以使用以下命令将枚举转换为字符串:
var enumValue = EducationG.BachelorOfArtsBA;
var attrs = (DescriptionAttribute[])typeof(EducationG)
.GetField(enumValue.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute));
var stringValue = attrs[0].Description;
将字符串转换回枚举更具挑战性:
var stringValue = ...
var enumValue =
from f in typeof(EducationG).GetFields(BindingFlags.Static)
from d in (DescriptionAttribute[])f.GetCustomAttributes(typeof(DescriptionAttribute))
where d.Description == stringValue
select f.GetValue(null);
无论如何,这个解决方案可能比您的特定问题更加复杂。
答案 1 :(得分:0)
枚举不包含字符串。 documentation对此进行了如下描述:
enum关键字用于声明枚举,这是一种由称为枚举器列表的命名常量组成的不同类型。每个枚举类型都有一个基础类型,除了char之外,它可以是任何整数类型。枚举元素的默认基础类型是int。默认情况下,第一个枚举数的值为0,每个连续枚举数的值增加1。
也许您正在寻找的是一个字符串数组。
string[] EducationG = {
"Bachelor of Arts (B.A)",
"Bachelor of Arts (Bachelor of Education (B.A. B.Ed)",
....
}
如果您只想将一串字符串添加到组合框中,那么字符串数组就可以了。但是如果你确实需要枚举,那么你将需要声明一个enum
并找到一种在枚举值和字符串名称之间进行映射的方法。 Description
属性可以解决问题。
答案 2 :(得分:0)
请参阅链接中的示例 emun(C#)代码可能类似于:
public enum EducationG {SomeName, SomeOtherName};
正如您在链接中注意到的,您还可以在枚举中添加默认值和标志。
答案 3 :(得分:0)
您还可以使用List<string>
,如下所示:
var educationGrades = new List<string>
{
"Bachelor of Arts (B.A)",
"Bachelor of Arts (Bachelor of Education (B.A. B.Ed)",
...
"Bachelor of Computer Science (B.C.S)"
};
答案 4 :(得分:0)
使用字符串并像这样编码
private void edulvlcb_SelectedIndexChanged(object sender, EventArgs e)
{
combobox.Items.Clear();
foreach (string ug in Classname.stringname)
combobox.Items.Add(ug);
}
必须有效