C#:根据不同枚举类型的枚举值返回枚举值

时间:2010-06-23 01:10:35

标签: c# enums

所以我希望有一个属性getter,它根据不同类型的枚举值返回枚举值,而不必求助于long switch语句。有没有办法使用一个或多个索引来匹配两个枚举列表?

public enum LanguageName
    {
        Arabic,
        Chinese,
        Dutch,
        English,
        Farsi,
        French,
        Hindi,
        Indonesian,
        Portuguese,
        Spanish,
        Urdu
    }

    public enum LanguageISOCode
    {
        ara,
        zho,
        dut,
        eng,
        fas,
        fre,
        hin,
        ind,
        por,
        spa,
        urd
    }

public class language
{
    public language()
    {
    }

    public LanguageName Name
    {
        get
        {
           // get the Name enum based on the Code enum
        }
        set;
    }

    public LanguageISOCode Code
    {
        get;
        set;
    }
}

4 个答案:

答案 0 :(得分:8)

您可以明确声明一个枚举值等于另一个,如下所示:

public enum LanguageName
{
    Arabic,
    Chinese,
    Dutch,
    ...
}

public enum LanguageISOCode
{
    ara = LanguageName.Arabic,
    zho = LanguageName.Chinese,
    dut = LanguageName.Dutch,
    ...
 }

然后你可以在他们之间施放:

 LanguageISOCode codeValue = LanguageISOCode.ara;

 LanguageName name = (LanguageName)(int)codeValue;

 LanguageName nameValue = LanguageName.Arabic;

 LanguageISOCode = (LanguageISOCode)(int)nameValue;

虽然以上内容应该回答您的明确问题,但您应该查看System.Globalization.CultureInfo课程。它为各种文化提供了相当多的功能。

答案 1 :(得分:3)

您可以使用Dictionary<LanguageName, LanguageISOCode>将其中一个显式映射到另一个。

Dictionary<LanguageName, LanguageISOCode> languageCodes = new Dictionary<LanguageName, LanguageISOCode> {
  {LanguageName.Arabic,LanguageISOCode.ara},
  {LanguageName.Chinese,LanguageISOCode.zho},
  //...
};

LanguageName lang = LanguageName.Arabic;
LanguageISOCode code = languageCodes[lang];

答案 2 :(得分:2)

假设值的顺序相同,您可以先进行int转换:

public LanguageName Name
{
    get
    {
        int n = (int) Code;
        return (LanguageName)n;
    }
}

这需要确保您的枚举值始终是正确的顺序,或者您明确地为它们分配数值:

public enum LanguageName
{
    Arabic = 1,
    Chinese = 2,
    ...
}

public enum LanguageISOCode
{
    ara = 1,
    zho = 2,
    ...
}

以上不是必需的(因为标准保证它们可以分配单调增加的数值),但至少它会在您决定重新排序字段或类似事件的情况下覆盖您。

答案 3 :(得分:1)

您可以在两者中使用相同的int值,并将其转换为int并转换为枚举。

public enum LanguageName
    {
        Arabic = 1,
        Chinese,
        Dutch,
        English,
        Farsi,
        French,
        Hindi,
        Indonesian,
        Portuguese,
        Spanish,
        Urdu
    }

    public enum LanguageISOCode
    {
        ara = 1,
        zho,
        dut,
        eng,
        fas,
        fre,
        hin,
        ind,
        por,
        spa,
        urd
    }

public class language
{
    public language()
    {
    }

    public LanguageName Name
    {
        get
        {
           return (LanguageName)((int)Code);
        }
        set;
    }

    public LanguageISOCode Code
    {
        get;
        set;
    }
}

或者您可以使用其他方法,例如使用[描述]并进行一些搜索。