我最近在我的代码中不再使用枚举,而是使用具有受保护构造函数和预定义静态实例的类(感谢 Roelof - C# Ensure Valid Enum Values - Futureproof Method)。
鉴于此,下面是我现在处理这个问题的方式(包括隐式转换到/从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 中)时尚)而不是在整个代码中放置大量案例语句来处理每种情况。
注意:答案于 2018-04-27 更新以利用 C# 6 功能;即声明表达式和 lambda 表达式主体定义。查看原始代码的修订历史。这样做的好处是使定义不那么冗长;这是对此答案方法的主要抱怨之一。