简体   繁体   中英

How to iterate through “set” enum in .NET C# 3.5

I know in .NET 4 you can use HasFlag

Is there any alternative to the following in .NET 3.5?

if ((enumVar & EnumType.ValueOne) == EnumType.ValueOne)
{
  // someMethod(1) or someMethod(EnumType.ValueOne)
}
if ((enumVar & EnumType.ValueTwo) == EnumType.ValueTwo)
{
  // someMethod(2) or someMethod(EnumType.ValueTwo)
}
if ((enumVar & EnumType.ValueThree) == EnumType.ValueThree)
{
  // someMethod(3) or someMethod(EnumType.ValueThree)
}
if ((enumVar & EnumType.ValueFour) == EnumType.ValueFour)
{
  // someMethod(4) or someMethod(EnumType.ValueFour)
}

...etc for each value in the enum? You must be able to use a for..each loop to accomplish this where the argument to someMethod is the index of the loop?

[Flags]
enum EnumType
{
  ValueOne = 1
  , ValueTwo = 2
  , ValueThree = 4
  , ValueFour = 8
}

EDIT: Only worth looking at the accepted answer, the rest of the comments/answers can be safely ignored.

You should be able to write something like this. You can make it generic if you want, but there's no way to set the constraint to be enum, so you'd have to check that yourself with reflection.

public static bool HasFlag(YourEnum source, YourEnum flag)
{
    return (source & flag) == flag;
}
foreach (EnumType enumType in Enum.GetValues(typeof(EnumType)))
{
    if(enumVar.HasFlag(enumType)) 
    {
        Console.WriteLine(enumTpye.ToString());
    }
}

You can do something like this to do a foreach loop of EnumType

foreach (EnumType enumType in Enum.GetValues(typeof(EnumType)))
{
    if (enumType.HasFlag(enumType))
    {
        Console.WriteLine(enumType.ToString());
    }
}

This will return ValueOne, ValueTwo, ValueThree.. etch not sure if this is what you are looking for please test and let me as well as others know

switch enumvar
{
case valueOne:
{
//do some thing
breake;
}
case valuetwo:
{
//do some thing else
break;
}
default:
break;
    }

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