简体   繁体   中英

Casting to invalid enum value, Enum.ToObject, does not throw exception, sets Enum to int

Is this normal behavior?

Writing an enum casting for

1) Try text parsing 2) Fallback to int parsing.

int parsing never throws an error...

Try running the following script in LinqPad, I haven't tested other compilers than linqpad, but I doubt it's an Linqpad issue.

How can I throw an error if int matching fails ?

void Main()
{
    FieldAttributes fieldattributeenum = FieldAttributes.Assembly;
    B b = B.Valx1;      
    b.Dump("B = "+((int)b).ToString()); //Valx1 (11);

    fieldattributeenum.Dump("fieldattributeenum = " +((int)fieldattributeenum).ToString()); //Assembly (3)

    b = (B) Enum.ToObject(typeof(B), (int) fieldattributeenum); 
    b.Dump("B = "+((int)b).ToString()); //valcorrect3 (3)
    A a = (A) Enum.ToObject(typeof(A), (int) fieldattributeenum); //
    a.Dump("A = "+ ((int)a).ToString()); // ??? (3) 
}

public enum B{  
    Valx1=11,
    Valx2=12,
    Valx3=13,
    Valx4=14,
    valcorrect3 = 3
}
public enum A{  
    Valx1=11,
    Valx2=12,
    Valx3=13,
    Valx4=14,
    valcorrect3
}

Just use Enum.IsDefined . Basically enums are just ints and you can assign any int to an enum even if it isn't defined.

if(!Enum.IsDefined(typeof(A), a))
{
    throw new InvalidCastException("Not a valid value for A: " + a);
}

From MSDN Enum.ToObject Method (Type, Int32)

The ToObject(Type, Int32) method converts value to an enumeration member whose underlying value is value. Note that the conversion succeeds even if value is outside the bounds of enumType members. To ensure that value is a valid underlying value of the enumType enumeration, pass it to the IsDefined method.

So it is by design.

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