简体   繁体   中英

Pass Multiple Enum Values To Method

I have one enum and one function like this

        enum DaysOfWeek
        {
           Sunday = 1,
           Monday = 2,
           Tuesday = 4,
           Wednesday = 8,
           Thursday = 16,
           Friday = 32,
           Saturday = 64
        }

        public void RunOnDays(DaysOfWeek days)
        {
           // Do your work here..
        }

    // Im Calling The Function like this and passing the parameters with Pipe Seprated
       RunOnDays(DaysOfWeek.Tuesday | DaysOfWeek.Thursday);

Now Scenario is In MY UI I have some checkboxes like Monday to sunday and user can select all days or can select at least one. And I want to pass the selected values to my function RunOnDays. So it can be single value or many values. How I can pass values dynamically to that method on the selection of user.

Use [Flags] attribute on your enum

[Flags]
enum DaysOfWeek
{
   Sunday = 1,
   Monday = 2,
   Tuesday = 4,
   Wednesday = 8,
   Thursday = 16,
   Friday = 32,
   Saturday = 64
}

public void RunOnDays(DaysOfWeek days)
{
           // Do your work here..
}

It is easier to pass them through a List<T> or IEnumerable<T> .

public void RunOnDays(IEnumerable<DaysOfWeek> days)
{
    // do something amazing
}

public void DoWork()
{
    var days = new List<DaysOfWeek>();

    // put each checked day into days

    RunOnDays(days);
}

EDIT: If I understand your post correctly, you are asking how to dynamically apply the | operator to an indeterminate list of enums, correct? If RunOnDays is defined in an unmodifiable DLL, you first need to know if it supports compounded enums. If so, you can still use the IEnumerable approach and combine through iteration.

DaysOfWeek checkedDays;

foreach (var day in days)
{
    checkedDays |= day;
}

RunOnDays(checkedDays);

Ok, I'm not entirely sure what you need to know, but I'm going to have a guess.

Assume you have one checkbox per day, called mondayCheckbox , tuesdayCheckbox and so on.

Now you want to get a single int value that represents which of those checkboxes are selected.

You can do that as follows:

DaysOfWeek days = 0;

if (mondayCheckbox.Checked)
    days |= DaysOfWeek.Monday;

if (tuesdayCheckbox.Checked)
    days |= DaysOfWeek.Tuesday;

... And so on up to:

if (sundayCheckbox.Checked)
    days | = DaysOfWeek.Sunday;

if (days != 0)
{
    RunOnDays(days);
}
else
{
    // Handle no days selected.
}

I think you should also add a None to your DaysOfWeek enum:

[Flags]
enum DaysOfWeek
{
   None   = 0,
   Sunday = 1,

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