我想限制用户使用任何枚举值。如果用户试图分配两个以上的值,我必须抛出一个错误。
public enum Fruits
{
Apple,
Orange,
Grapes
}
public Fruits Fruits
{
get
{
return m_fruits;
}
set
{
m_fruits=value;
}
}
Fruits = Fruits.Apple & Fruits.Grapes; //I need to avoid such type of assignment
谁能说说如何检查这种类型的验证。
谢谢, 洛克什
最佳答案
您可以使用 Enum.IsDefined
查看是否确实为枚举定义了整数值。为了能够检测到没有逻辑操作,例如 Fruits.Apple | Fruits.Grapes
已被使用确保您的枚举值是标志。
public enum Fruits
{
Apple = 1,
Orange = 2,
Grapes = 4
}
public Fruits Fruit
{
get
{
return m_fruits;
}
set
{
if (!Enum.IsDefined(typeof(Fruits), value))
{
throw new ArgumentException();
}
m_fruits = value;
}
}
更新:
没有反射的更快方法是自己检查所有枚举值:
public Fruits Fruit
{
get
{
return m_fruits;
}
set
{
switch (value)
{
case Fruits.Apple:
case Fruits.Grapes:
case Fruits.Orange:
m_fruits = value;
break;
default:
throw new ArgumentException();
}
}
}
关于c# - 如何检查枚举变量是否分配有单个枚举值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3657946/