【问题标题】:C# Difference betwen passing multiple enum values with pipe and ampersandC# 使用管道和 & 符号传递多个枚举值之间的差异
【发布时间】:2011-05-07 05:35:23
【问题描述】:

C# 接受这个:

this.MyMethod(enum.Value1 | enum.Value2);

还有这个:

this.MyMethod(enum.Value1 & enum.Value2);

有什么区别?

【问题讨论】:

  • 通过enum.Value1 & enum.Value2 的可能性很小。

标签: c# .net parameters enums parameter-passing


【解决方案1】:

当您执行| 时,您会同时选择两者。当你做&时,你只会重叠。

请注意,这些运算符仅在将 [Flags] 属性应用于枚举时才有意义。有关此属性的完整说明,请参阅 http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx

例如,以下枚举:

[Flags]
public enum TestEnum
{
    Value1 = 1,
    Value2 = 2,
    Value1And2 = Value1 | Value2
}

还有一些测试用例:

var testValue = TestEnum.Value1;

在这里我们测试testValueValue1And2 重叠(即是其中的一部分):

if ((testValue & TestEnum.Value1And2) != 0)
    Console.WriteLine("testValue is part of Value1And2");

这里我们测试testValue是否完全等于Value1And2。这当然不是真的:

if (testValue == TestEnum.Value1And2)
    Console.WriteLine("testValue is equal to Value1And2"); // Will not display!

这里我们测试testValueValue2的组合是否正好等于Value1And2

if ((testValue | TestEnum.Value2) == TestEnum.Value1And2)
    Console.WriteLine("testValue | Value2 is equal to Value1And2");

【讨论】:

    【解决方案2】:
    this.MyMethod(enum.Value1 | enum.Value2);
    

    这会将两个枚举值按位“或”在一起,因此如果enum.Value 为 1 且enum.Value2 为 2,则结果将是 3 的枚举值(如果存在,否则它将只是整数 3 )。

    this.MyMethod(enum.Value1 & enum.Value2);
    

    这会将两个枚举值按位“与”在一起,因此如果 enum.Value 为 1,enum.Value2 为 3,则结果将为 1 的枚举值。

    【讨论】:

      【解决方案3】:

      一个是按位或,另一个是按位与。在前一种情况下,这意味着在一个或另一个中设置的所有位都在结果中设置。在后一种情况下,这意味着在结果中设置了所有共同的并在两者中设置的位。您可以在 Wikipedia 上阅读有关 bitwise operators 的信息。

      例子:

      enum.Value1 = 7  = 00000111
      enum.Value2 = 13 = 00001101
      

      然后

      enum.Value1 | enum.Value2 = 00000111
                                 |00001101
                                = 00001111
                                = 15
      

      enum.Value1 & enum.Value2 = 00000111
                                 &00001101
                                = 00000101   
                                = 5
      

      【讨论】:

        【解决方案4】:

        这个问题有一个很好的解释:What does the [Flags] Enum Attribute mean in C#?

        【讨论】:

        【解决方案5】:

        枚举参数可以是二进制数,例如

        enum WorldSides
        {
            North=1,
            West=2,
            South=4,
            East=8
        }
        
        WorldSides.North | WorldSides.West = both values -> 3
        

        所以,|用于组合值。

        使用 & 去掉部分值,例如

        if (ws & WorldSides.North)
        {
             //  ws has north component
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-11-14
          • 2011-12-21
          • 2023-03-31
          • 1970-01-01
          • 2010-11-05
          • 2016-10-06
          • 1970-01-01
          • 2014-08-13
          相关资源
          最近更新 更多