下面我在一个枚举变量中设置三个枚举常量,有没有办法从枚举变量中检索枚举常量作为数组?
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Fruits fruit1 = Fruits.Apple;
Fruits fruit2 = Fruits.Mango;
Fruits mixedFruits = Fruits.Apple | Fruits.Orange | Fruits.Banana;
string allFruits = mixedFruits.ToString();
// I want the output to be "Apple, Orange, Banana"
//Is this possible??
}
}
public enum Fruits
{
Apple,
Mango,
Orange,
Grapes,
Banana,
}
Run Code Online (Sandbox Code Playgroud)
您必须使用[Flags]属性并将枚举值设置为2的幂:
[Flags]
public enum Fruits
{
Apple = 1,
Mango = 2,
Orange = 4,
Grapes = 8,
Banana = 16
}
Run Code Online (Sandbox Code Playgroud)
现在,allFruits.ToString()将打印"Apple, Orange, Banana".