简体   繁体   中英

C# How to check an enum value is passed in a parameter?

I have a method which accepts an enum as an argument:

[Flags]
public enum MyEnum
{
  A = 1,
  B = 2,
  C = 3
}

public class MyClass
{
  public MyEnum myEnum;
}

public bool MyMethod(MyClass class, MyEnum enumParam)
{
  // Here I want to check if object class contains some enum values passed as an argument
  // Something like: if(class.myEnum 'contains-one-of-the-items-of enumParam)
}

public void Test()
{
  Myclass class = new MyClass() { myEnum = MyEnum.A };
  MyMethod(class, MyEnum.A | MyEnum.B);
}

I want to check if an object contains one of the enum values which are passed in the method as an argument.

作为您的使用标志,这可以帮助您检查是否已设置枚举值: [Flags]枚举属性在C#中是什么意思?

You can write it like this

public bool MyMethod(MyClass class, MyEnum enumParam)
{
  if( (enumParam & MyEnum.A) != 0 ){
    ...
  }
  if( (enumParam & MyEnum.B) != 0 ){
    ...
  }
}

I changed enum to enumParam to not conflict with the enum keyword.

There is also a problem with your implementation since you have the values 1,2,3 for A,B,C. This way you can't differentiate between A+B=3 and C=3. A should be 1, B should be 2 and C should be 4 (D should be 8 and so on)

EDIT

Edit due to OP's comment.

public bool MyMethod(MyClass class, MyEnum enumParam)
{
  return Enum.IsDefined(typeof(MyEnum), enumParam);
}

If you want to see if any of the values passed in the parameter are in the class's myEnum field, you can write:

public bool MyMethod(MyClass class, MyEnum enum)
{
  // Here I want to check if object class contains some enum values passed as an argument
  // Something like: if(class.myEnum 'contains-one-of-the-items-of enum)
  return (this.myEnum & enum) != 0;
}

This does a logical "AND" of the bit flags and will return true if any one of the flags in enum is set in myEnum .

If you want to ensure that all the flags are set, then you can write:

return (this.myEnum & enum) == this.myEnum;

Also, read the response by @Øyvind Bråthen carefully. In order for [Flags] to work, you need to ensure that your enum values are powers of 2.

Change your enum like this :

public enum MyEnum
    {
        A = 2,
        B = 4,
        C = 8
    }

and your method is as simple as :

public bool MyMethod(MyClass aClass, MyEnum aEnum)
        {
            return (aClass.myEnum & aEnum) != 0;
        }

Best regards

In C# 4.0 you can easily use Enum.HasFlag method. You can take a look at this question to get other solutions including C# 3.5 and previous versions.

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