开发者

How to check whether an enum variable is assigned with a single enum value?

I would like to restrict the user to use any of the enumvalue.if the user tries to assign more than two values,i have to throw an error.

public enum Fr开发者_JAVA百科uits
{
    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

Can anyone say how to check this type of validation.

Thanks, Lokesh


You can use Enum.IsDefined to see whether an integral value is actually defined for an enum. In order to be able to detect that no logical operation such as Fruits.Apple | Fruits.Grapes has been used make sure that your enum values are flags.

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;
    }
}

Update:

A faster method without reflection would be to check all enum values yourself:

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();
        }
    }
}


You can use the Enum.IsDefined() method to check whether a value is a valid enum value:

Fruits f1 = Fruits.Orange;
Fruits f2 = (Fruits)77;

var b1 = Enum.IsDefined(typeof(Fruits), f1); // => true
var b2 = Enum.IsDefined(typeof(Fruits), f2); // => false

BTW: Your example seems incorrect: var f = Fruits.Apple&Fruits.Grapes will assign Fruits.Apple to f. This is because a bitwise AND of Apple (==0) and Grapes (==2) will result in 0 (which still is a valid enum value -> Apple).

If you meant something like var f = Fruits.Orange|Fruits.Grapes, then f will now be 3 (bitwise OR of 1 and 2) and Enum.IsDefined will now return false.


That is a bitwise operation, and can only be used in conjunction with the [Flags] attribute, and when you're values for your enum are explicitly applicable to flags (e.g. 1, 2, 4, 8, 16, etc.)


You can't restrict it. The only way to do it to create custom class and create static fields with instances (like Encoding). By the way, bitwise & is meaningless for enum that is not marked as [Flags]. Fruits.Apple&Fruits.Grapes will not set two values (| does), it will produce meaningless result: since by default enums are mapped to sequence of ints Fruits.Apple&Fruits.Grapes will produce Fruits.Apple because Apple is mapped to 0

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜