I have an int and I want to know the corresponding enum value.
Actually have an enum and I want to return the corresponding value for another enum.
I might just use a large switch but I would like to know if there is a better way.
Something like this?
MyEnum m = (MyEnum)((int)otherEnum);
var en = (StringSplitOptions)SeekOrigin.Begin;
How do the two enum
types "correspond"? If there is no direct link, then yes, a large switch
statement will be necessary. Otherwise, if they have the same underlying value, then you can simply cast from one type to the other. If you have an int
, you can also cast that to the desired enum
type.
There are two cases, one where the enums are sharing the values, and one when they are sharing the name. You can cast the values and parse the names as shown here. If neither the names nor the values are the same you of course can't do this.
public void Test() {
var one = FirstEnumWithSameValues.Two;
var two = (SecondEnumWithSameValues) one;
var three = FirstEnumWithSameName.Two.ToString();
var four = (SecondEnumWithSameName) Enum.Parse(typeof(SecondEnumWithSameName), three);
}
public enum FirstEnumWithSameValues
{
One = 1,
Two = 2,
Three = 3
}
public enum SecondEnumWithSameValues
{
Uno = 1,
Due = 2,
Trez = 3
}
public enum FirstEnumWithSameName
{
One = 1,
Two = 2,
Three = 3
}
public enum SecondEnumWithSameName
{
One = 4,
Two = 5,
Three = 6
}
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.