简体   繁体   中英

How to read enum int value (without converting via cast) in C#?

I had the following:

public enum SearchSex {
    All = 0,
    Male = 1,
    Female = 2,
    Other = 3
}

Now I have this, to allow for Flags and bitmasking:

public enum SearchSex {
    All = 1,
    Male = 2,
    Female = 4,
    Other = 8
}

In production, I want all of the settings to remain the same as we make this update. So I have a script that is doing the following:

// for each user:  
user.SearchSex= (SearchSex)(Math.Pow(2, (Convert.ToInt32(user.SearchSex) - 1)));

I was thinking the Convert.ToInt32 would return the (old) actual integer value from the database, but it's trying to map the integer value to those (new) defined in the Enum definition. How do I go about reading the raw integer value as it is, even if there is no longer any corresponding Enum value defined?

Why not just execute a query on the database? Something like

UPDATE usertable SET SearchSex = POWER(2, SearchSex);

Of course, I recommend you run a select query first.

SELECT *, Power(2, SearchSex) AS NewSearchSex FROM usertable;

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