c# - 如何检查枚举变量是否分配有单个枚举值?

标签 c#

我想限制用户使用任何枚举值。如果用户试图分配两个以上的值,我必须抛出一个错误。

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/

相关文章:

c# - 如何在 Kendo UI MVC 的网格中设置和获取下拉列表的值?

c# - 获取给定某一天的一周中的天数范围

c# - base() 和 this() 构造函数最佳实践

c# - 我应该捕获所有可能的特定异常还是只是一般异常并将其包装在自定义异常中?

c# - Entity Framework SqlQuery使用重复参数执行查询

c# - 使 DateTimePicker 仅在 WinForms 中用作 TimePicker

c# - umbraco 7.1 注销(razor 语法 C#)

c# - 您可以命名 Func<T> 类型的参数吗?

c# - 页面退出时执行操作

c# - WebAPI 在 IIS 中不返回 xml