最近,我不再使用代码中的枚举,而是改为使用具有受保护的构造函数和预定义的静态实例的类(这要归功于Roelof- C#确保有效的枚举值-Futureproof方法)。
有鉴于此,以下是我现在如何解决此问题的方法(包括隐式转换为或从转换为int
)。
public class Question
{
// Attributes
protected int index;
protected string name;
// Go with a dictionary to enforce unique index
//protected static readonly ICollection<Question> values = new Collection<Question>();
protected static readonly IDictionary<int,Question> values = new Dictionary<int,Question>();
// Define the "enum" values
public static readonly Question Role = new Question(2,"Role");
public static readonly Question ProjectFunding = new Question(3, "Project Funding");
public static readonly Question TotalEmployee = new Question(4, "Total Employee");
public static readonly Question NumberOfServers = new Question(5, "Number of Servers");
public static readonly Question TopBusinessConcern = new Question(6, "Top Business Concern");
// Constructors
protected Question(int index, string name)
{
this.index = index;
this.name = name;
values.Add(index, this);
}
// Easy int conversion
public static implicit operator int(Question question) =>
question.index; //nb: if question is null this will return a null pointer exception
public static implicit operator Question(int index) =>
values.TryGetValue(index, out var question) ? question : null;
// Easy string conversion (also update ToString for the same effect)
public override string ToString() =>
this.name;
public static implicit operator string(Question question) =>
question?.ToString();
public static implicit operator Question(string name) =>
name == null ? null : values.Values.FirstOrDefault(item => name.Equals(item.name, StringComparison.CurrentCultureIgnoreCase));
// If you specifically want a Get(int x) function (though not required given the implicit converstion)
public Question Get(int foo) =>
foo; //(implicit conversion will take care of the conversion for you)
}
这种方法的优点是您可以从枚举中获得所有内容,但是您的代码现在更加灵活,因此,如果需要根据的值执行不同的操作Question
,则可以将逻辑放入Question
自身(即,在首选的OO中)时尚),而不是在整个代码中放置大量case语句来解决每种情况。
注意:答案已于2018-04-27更新,以利用C#6功能; 即声明表达式和lambda表达式主体定义。有关原始代码,请参见修订历史记录。这样做的好处是使定义不再那么冗长。这是对该答案方法的主要抱怨之一。