为枚举元素指定多个值

嗨,我目前有这个枚举

[Serializable] public enum Country { US = 1, Canada = 2, } 

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

 (Country) Convert.ToInt32("1") 

我现在在美国和加拿大有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 } 

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

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... } 

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

你必须做这样的事情:

 class Region { static readonly RegionMap = new Dictionary { { 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; } } 

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

 string region = Region.GetRegion(dbVal); 

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

 [Serializable] [Flags] public enum Country { US = 1, Canada = 2, Northern = 4, Southern = 8 } 

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

也许是这样的?

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

啊我只使用了一个函数而不是直接进行类型转换。 实现完全不同的东西要容易得多。 我已经有很多代码在运行,所以不能改变它,但这就是我所做的。

 public Country GetCountryByTaxID(int taxID) { if (taxID == 3 || taxID == 4) { return Country.USA; } else { return Country.Canada; } } 
 public Country GetCountry(int a) { if (a == 1 || a == 2) { return Country.USA; } else if (a == 4|| a == 3) { return Country.Canada; } } 

这对我来说就像一个问题,其中1和2在我们的集合中,3和4在集合加拿大。 代码项目中有一些设置代码,我认为更好地模拟了问题。

除了dtb的答案(以及那些相同的建议),我刚刚在我的应用程序的命名空间中实现了一个’重写’版本的System.Convert

 public static class Convert { public static object ChangeType (object value, Type conversionType, IFormatProvider provider) { int country; if (conversionType == typeof(Country) && int.TryParse(value.ToString(), out country)) { switch (country) { case 1: case 2: return Country.US; case 3: case 4: return Country.Canada; } } // For most cases, including any country unmatched above... return System.Convert.ChangeType(value, conversionType, provider); } } 

现在,mscorlib.dll Convert类的原始方法必须以“ System. ”为前缀,因此欢迎任何改进!