C#:根据不同枚举类型的枚举值返回枚举值
因此,我想要一个属性 getter,它根据不同类型的枚举值返回一个枚举值,而不必求助于长 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;
}
}
So I want to have a property getter that returns an enum value based on an enum value of a different type without having to resort to a long switch statement. Is there a way to match up the two enum lists using an index or values?
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以显式声明一个枚举值等于另一个枚举值,如下所示:
然后您可以在它们之间进行转换:
或者
虽然上面应该回答您的明确问题,但您应该看看
System.Globalization.CultureInfo
类。它提供了很多关于不同文化的功能。You can explicitly declare that one enum value is equal to another, like so:
Which will then let you cast between them:
or
While the above should answer your explicit question, you should have a look at the
System.Globalization.CultureInfo
class. It provides quite a bit of functionality regarding various cultures.您可以使用
Dictionary
将一种语言显式映射到另一种语言。You can use
Dictionary<LanguageName, LanguageISOCode>
for explicit mapping of one to the other.假设这些值的顺序相同,您可以先进行
int
转换:这需要确保您的枚举值始终处于正确的顺序,或者您明确地为它们分配数值:
上述内容不是必需的(因为标准保证它们分配单调递增的数值),但至少它涵盖了您可能决定重新排序字段或类似情况的情况。
Assuming the values are in the same order, you can just go through an
int
conversion first:This would require that make sure your enumerated values are always in the right order, or that you explicitly assign them numerical values:
The above is not required (since the standard guarantees that they get assign monotonically increasing numerical values) but at least it covers you in the case where you might decide to reorder fields, or something like that.
您可以在两者中使用相同的 int 值,并强制转换为 int 和强制转换为 enum。
或者您可以使用另一种方法,例如使用[描述]并进行一些搜索。
You can use same int value in both, and cast as int and cast as enum.
Or you can use another approach, like use [Description] and make some search.