-2

我已使用枚举类型数据类型在 Windows 窗体 c# 的组合框中添加字符串元素,但在其中添加元素时出现错误。错误是 ("Identifier Expected") 我的代码是

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)")
}
4

5 回答 5

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

无论如何,这个解决方案可能比您的特定问题更复杂。

于 2013-03-31T17:15:34.723 回答
0

枚举不包含字符串。文档是这样描述它们的:

enum 关键字用于声明一个枚举,一种由一组称为枚举数列表的命名常量组成的独特类型。每个枚举类型都有一个底层类型,它可以是除 char 之外的任何整数类型。枚举元素的默认基础类型是 int。默认情况下,第一个枚举器的值为 0,并且每个后续枚举器的值都增加 1。

也许您正在寻找的是一个字符串数组。

string[] EducationG = {
    "Bachelor of Arts (B.A)",
    "Bachelor of Arts (Bachelor of Education (B.A. B.Ed)",
    ....
}

如果您只想将一堆字符串添加到组合框中,那么字符串数组就可以了。但是如果你真的需要一个枚举,那么你会想要声明一个enum并找到一种在枚举值和字符串名称之间进行映射的方法。该Description属性可以解决问题。

于 2013-03-31T17:15:42.737 回答
0

请参阅链接 emun(C#)中的示例,代码可能类似于:

public enum EducationG {SomeName, SomeOtherName};

正如您将在链接中注意到的那样,您还可以向枚举添加默认值和标志。

于 2013-03-31T17:19:02.883 回答
0

您还可以使用List<string>如下所示的 a:

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)"
};
于 2013-03-31T17:47:01.310 回答
0

像这样使用字符串和justcode

private void edulvlcb_SelectedIndexChanged(object sender, EventArgs e)
        {

                   combobox.Items.Clear();
            foreach (string ug in Classname.stringname)
                combobox.Items.Add(ug);
    }

它必须工作

于 2013-04-30T11:40:05.940 回答