简体   繁体   中英

C# ValidationAttribute for enums

I have the following enums:

public enum FirstEnum : short
{
    Unknown = -1,
    Red = 2,
    Green = 3
}

public enum SecondEnum 
{
    Unknown = -1,
    Orange = 2,
    Apple = 3
}

I now want to write a data annotation attribute so I can validate properties. So say I have a class:

public class MyClass
{
    [EnumValidation(AllowUnKnown = true)]
    public FirstEnum  First { get; set; }

    [EnumValidation(AllowUnKnown = false)]
    public SecondEnum  Second { get; set; }
}

and my validation attribute is as follows:

public class EnumValidationAttribute : ValidationAttribute
{
    public bool AllowUnKnown { get; set; }

    public override bool IsValid(object aValue)
    {
        bool valid = true;
        int enumValue = (int) aValue;  //** Cannot do hard cast
        if (enumValue == -1 && !AllowUnKnown)
                valid = false;

        return valid;
    }
}

so now he issue comes in that I can no longer do a hard cast of the enum member to an int as FirstEnum is a short.

So how do I safely determine the value for the enum member? (I cannot change the declaration of FirstEnum)

First of all you can't use -1 value for byte variable then you should change Unknown value to any other valid byte . FirstEnum is not compilable.

Also, you can use Convert.ToInt32 method to cast byte value to integer. Actually, next code write true to the console:

byte x1 = 1;
object o1 = x1;
Console.WriteLine(Convert.ToInt32(o1) == 1);

So you can implement your method with convertation:

public override bool IsValid(object aValue)
{
    int enumValue = Convert.ToInt32(aValue);
    return !(enumValue == -1 && !AllowUnKnown);
}

这个工作:

int enumValue = Convert.ToInt32(b); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM