我有一门课叫问题(复数)。在这个类中有一个名为Question(单数)的枚举,看起来像这样。
public enum Question
{
Role = 2,
ProjectFunding = 3,
TotalEmployee = 4,
NumberOfServers = 5,
TopBusinessConcern = 6
}
在Questions类中,我有一个get(intfoo)函数,它为该foo返回Questions对象。有没有一种简单的方法可以从枚举中获取整数值,这样我就可以执行类似于Questions.get(Questions.Role)的操作?
最近,我不再在代码中使用枚举,而是使用带有受保护构造函数和预定义静态实例的类(感谢Roelof-C#确保有效枚举值-Futureproof方法)。
鉴于此,下面是我现在如何处理这个问题(包括隐式转换为int或从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表达式体定义。原始代码参见修订历史。这样做的好处是使定义不那么冗长;这是对这个答案方法的主要抱怨之一。
如果您想为存储在变量中的枚举值获取一个整数(其类型为Question),以便在方法中使用,您可以简单地执行我在本例中编写的操作:
enum Talen
{
Engels = 1, Italiaans = 2, Portugees = 3, Nederlands = 4, Duits = 5, Dens = 6
}
Talen Geselecteerd;
public void Form1()
{
InitializeComponent()
Geselecteerd = Talen.Nederlands;
}
// You can use the Enum type as a parameter, so any enumeration from any enumerator can be used as parameter
void VeranderenTitel(Enum e)
{
this.Text = Convert.ToInt32(e).ToString();
}
这会将窗口标题更改为4,因为变量Geselecterd是Talen.Nedelands。如果我将其更改为Talen.Portuges并再次调用该方法,文本将更改为3。
public enum Suit : int
{
Spades = 0,
Hearts = 1,
Clubs = 2,
Diamonds = 3
}
Console.WriteLine((int)(Suit)Enum.Parse(typeof(Suit), "Clubs"));
// From int
Console.WriteLine((Suit)1);
// From a number you can also
Console.WriteLine((Suit)Enum.ToObject(typeof(Suit), 1));
if (typeof(Suit).IsEnumDefined("Spades"))
{
var res = (int)(Suit)Enum.Parse(typeof(Suit), "Spades");
Console.Out.WriteLine("{0}", res);
}
我最喜欢的int或更小enums黑客:
GetHashCode();
对于枚举
public enum Test
{
Min = Int32.MinValue,
One = 1,
Max = Int32.MaxValue,
}
这
var values = Enum.GetValues(typeof(Test));
foreach (var val in values)
{
Console.WriteLine(val.GetHashCode());
Console.WriteLine(((int)val));
Console.WriteLine(val);
}
输出
one
1
1
max
2147483647
2147483647
min
-2147483648
-2147483648
免责声明:
它不适用于基于long的枚举。