[英]Using enum type keys for a same value in c#
How can I associate 2 values into a single enum
type value in ac# application? 如何在ac#应用程序中将2个值关联到单个
enum
类型值? For example, I have a enum
type like this: 例如,我有一个这样的
enum
类型:
public enum person
{
soccerPlayer,
tennisPlayer,
athlete,
coach
}
A soccer player and a tennis player are athletes, but a coach is not an athlete. 足球运动员和网球运动员都是运动员,但教练不是运动员。
If I instance a person, like this: 如果我实例一个人,像这样:
person p = person.soccerPlayer;
How do I do this test? 我该怎么做这个测试?
if (p == person.athlete)
In this particular case you would be better served by having a function check to see if the enum
value is an athlete 在这种特殊情况下,您可以通过功能检查来查看
enum
值是否为运动员
static bool IsAthlete(person p) {
switch (p) {
case person.soccerPlayer:
case person.tennisPlayer:
case person.athlete:
return true;
default:
return false;
}
}
Overall though I don't believe an enum
type serves you well here. 总的来说,虽然我不相信
enum
类型在这里很好。 An enum
is typically used to represent mutually exclusive values (can be A or B but not both) or for bit flag situations. enum
通常用于表示互斥值(可以是A或B但不是两者)或用于位标志情况。 You could manipulate bit flags to work here but i feel like it isn't the best approach. 你可以操纵位标志在这里工作,但我觉得这不是最好的方法。
This is the type of situation which seems more suitable a full fledged type. 这种情况似乎更适合完全成熟的类型。
class Person {
public bool IsAthlete { get; private set; }
public bool IsSoccerPlayer { get; private set; }
public bool IsTennisPlayer { get; private set; }
public static readonly TennisPlayer = new Person {
IsTennisPlayer = true,
IsAthelete = true
}
public static readonly SoccerPlayer = new Person {
IsSoccerPlayer = true,
IsAthelete = true
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.