[英]Convert Enum into another Enum
I have two enums:我有两个枚举:
public enum Fruits
{
Apple = 1,
Banana = 2,
Strawberry = 3,
Blueberry = 4
}
public enum FruitsCombined
{
Apple = 1,
Banana = 2,
Berries = 0 //Strawberry and Blueberry combined
}
I have a Combobox, which is bound to the FruitsCombined
enum, but in the background, when I select Berries
, I want to say it's 3 and 4 from the Fruits
enum.我有一个 Combobox,它绑定到
FruitsCombined
枚举,但在后台,当我 select Berries
时,我想说它是Fruits
枚举中的 3 和 4。
How can I do this?我怎样才能做到这一点?
For example, I want to replace this for a better way, with the two enums:例如,我想用两个枚举替换它以获得更好的方法:
if ((int)cboFilterFruitType.SelectedValue == 0)
{
order = order.FindAll(o => o.FruitID == 3 || o.FruitID == 4);
}
else
{
order = order.FindAll(o => o.FruitID == (int) cboFilterFruitType.SelectedValue);
}
You can use flags
enums:您可以使用
flags
枚举:
[Flags]
public enum Fruits
{
Apple = 1,
Banana = 2,
Strawberry = 4,
Blueberry = 8
}
public enum FruitsCombined
{
Apple = 1,
Banana = 2,
Berries = Fruits.Strawberry | Fruits.Blueberry //Strawberry and Blueberry combined
}
Now you can cast one to the other:现在您可以将一个转换为另一个:
FruitsCombined fruitCombined = FruitsCombined.Berries;
Fruits fruit = (Fruits)fruitCombined; // Fruits.Strawberry | Fruits.Blueberry
If you want to check if it's a berry you can use Enum.HasFlag
:如果你想检查它是否是浆果,你可以使用
Enum.HasFlag
:
bool isBerry = fruit.HasFlag(Fruits.Strawberry | Fruits.Blueberry);
If you have control over both enums you could combine the enums together using flags like suggested in the comments.如果您可以控制这两个枚举,则可以使用评论中建议的标志将这些枚举组合在一起。
[Flags]
public enum Fruits
{
None = 0,
Apple = 1,
Banana = 2,
Strawberry = 4,
Blueberry = 8,
Berries = Strawberry | Blueberry
}
Then if you had code like this那么如果你有这样的代码
var fruit = Fruits.Berries;
Console.WriteLine(fruit.HasFlag(Strawberry));
Console.WriteLine(fruit.HasFlag(Blueberry));
Both write lines would print true.两条写入行都将打印为真。
as stuartd link says do something more like正如 stuartd 链接所说,做一些更像
change to powers of two变为二的幂
public enum Fruits
{
Apple = 1,
Banana = 2,
Strawberry = 4,
Blueberry = 8
}
Then you can use bitwise to represent any combo然后你可以使用 bitwise 来表示任何组合
var appBann = Fruits.Apple | var appBann = Fruits.Apple | Suits.Banana;
Suits.Banana;
or Berries = Fruits.Strawberry |或浆果 = Fruits.Strawberry | Suits.Blueberry
西装.蓝莓
you can even have it as a enum你甚至可以把它作为一个枚举
public enum Fruits
{
Apple = 1,
Banana = 2,
Strawberry = 4,
Blueberry = 8,
Berries = Strawberry | Blueberry
}
order = order.FindAll(o => o.FruitID == (int)Fruits.Berries);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.