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.


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.


作为你使用的标志,这可以帮助你检查是否已经设置了枚举值:[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);
}
链接地址: http://www.djcxy.com/p/54420.html

上一篇: 泛型枚举约束

下一篇: C#如何检查枚举值传递给参数?