简体   繁体   中英

Assign boolean value to array of enum types C#

From this enum type:

public enum MySqlObjectType
{
    Table = 1,
    Procedure = 2,
    View = 4,
    Function = 8,
    Trigger = 512,
    User = 128,
    Event = 256
}

I want to make something like this:

Options.Load[MySqlObjectType.Event] = true;
Options.Load[MySqlObjectType.Function] = false;

How field in Options class should look like so I can do something as above? And is it possible?

You just need a dictionary to store the enum -> boolean key/value pair:

public class Options
{
    public Options()
    {
        Load = new Dictionary<MySqlObjectType, bool>();
    }

    public Dictionary<MySqlObjectType, bool> Load { get; set; }
}

As Ivan said, you probably just want a simple flags enum:

public enum MySqlObjectType
{
    Table = 1,
    Procedure = 2,
    View = 4,
    Function = 8,
    Trigger = 512,
    User = 128,
    Event = 256
}

Note that all values should be powers of 2 and unique.

MySqlObjectType value = MySqlObjectType.Event | MySqlObjectType.User;

To check if a value is set, you can do:

if ((value & MySqlobjectType.Event) == MySqlObjectType.Event) {

I think you can also do this as of .NET Framework v4:

if (value.HasFlag(MySqlObjectType.Event)) {

An other way to create single flags enum is:

 public enum MySqlObjectType { Table = 1 << 0, Procedure = 1 << 1, View = 1 << 2, Function = 1 << 3, Trigger = 1 << 9, User = 1 << 7, Event = 1 << 8 } 

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