为枚举元素指定多个值

tHe*_*SiD 14 c# enums

嗨,我目前有这个枚举

[Serializable]
public enum Country
{
    US      = 1,
    Canada  = 2,
}
Run Code Online (Sandbox Code Playgroud)

当我通常从数据库中获取整数时,我将其转换为枚举使用

(Country) Convert.ToInt32("1")
Run Code Online (Sandbox Code Playgroud)

我现在在美国和加拿大有2个子区域,美国1和2,加拿大3和4.所以,当我这样做

(Country) Convert.ToInt32("1")或者(Country) Convert.ToInt32("2")我应该得到美国的枚举.以及3和4加拿大.我该如何实现?

[Serializable]
public enum Country
{
    US      = 1,2
    Canada  = 3,4
}
Run Code Online (Sandbox Code Playgroud)

像这样的东西.这可能不对,只是为了给你一个想法.

LBu*_*kin 13

一个enum可能不是这样的问题模型权结构.

我建议创建一个表示国家信息的类,并提供转换为数字表示的方法.对于这样的问题,您还必须确定将选定的Country实例转换为数值时将使用的编码值.

Enum对象模式可以为建模此类情况提供有用的起点:

public sealed class Country
{
    // initialize appropriately in the constructor...
    private readonly int[] m_Values;
    private readonly string m_Name;

    // make the constructor private so that only this class can set up instances
    private Country( string name, int[] codes ) { ... }

    public static Country US = new Country("United States", new[]{ 1,2 } );
    public static Country Canada = new Country("Canada", new[] {3,4} );

    public static Country FromCode( int code ) { ... }
    public override string ToString() { return m_Name; }
    // ... etc...
}
Run Code Online (Sandbox Code Playgroud)

根据您的示例,您还应该考虑是否需要将Country子区域建模为第一类实体,而不是简单地将它们折叠到Country枚举的实现细节中.您是否应该这样做取决于您的要求和用例,因此只有您可以做出适当的决定.


Fem*_*ref 11

这是不可能的.那你必须使用单独的值.如果名称相同,即.

[Serializable]
[Flags]
public enum Country
{
    US      = 1,
    Canada  = 2,
    Northern = 4,
    Southern = 8
}
Run Code Online (Sandbox Code Playgroud)

你可以这样做:Countries = Country.US | Country.Northern.如果没有,你需要找到另一种方式,可能是另一种方式,甚至更好,一Location类.


And*_*are 10

你必须做这样的事情:

class Region
{
    static readonly RegionMap = new Dictionary<int,string>
    {
        { 1, "US" },
        { 2, "US" },
        { 3, "Canada" }
        { 4, "Canada" }
    }

    public static string GetRegion(int code)
    {
        string name;
        if (!RegionMap.TryGetValue(code, out name)
        {
            // Error handling here
        }
        return name;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后根据数据库中的值查找字符串:

string region = Region.GetRegion(dbVal);
Run Code Online (Sandbox Code Playgroud)


dtb*_*dtb 6

也许是这样的?

static Country ConvertRegionToCountry(string region)
{
    switch (region)
    {
        case "1":
        case "2":
            return Country.US;

        case "3":
        case "4":
            return Country.Canada;
    }
}
Run Code Online (Sandbox Code Playgroud)


tHe*_*SiD 4

啊我只是使用了一个函数而不是直接类型转换。比实施完全不同的东西要容易得多。我已经在上面运行了很多代码,所以无法对其进行太多更改,但这就是我所做的。

public Country GetCountryByTaxID(int taxID)
        {
            if (taxID == 3 || taxID == 4)
            {
                return Country.USA;
            }
            else 
            {
                return Country.Canada;
            }
        }  
Run Code Online (Sandbox Code Playgroud)