4

在 C# 中,我试图将值“添加”到接受枚举标志的参数中。我可以使用按位运算符“|”在一行上执行此操作,但我似乎无法在循环中附加到参数。

我将以下枚举指定为标志。

[Flags]
public enum ProtectionOptions
{
  NoPrevention = 0,
  PreventEverything = 1,
  PreventCopying = 2,
  PreventPrinting = 4,
  PrintOnlyLowResolution = 8
}

现在,我可以轻松地使用以下代码向参数添加标志值:

myObj.Protection = ProtectionOptions.PreventEverything | ProtectionOptions.PrintOnlyLowResolution;

但是,我想做的是从 CSV 字符串(来自 Web.Config)中获取保护选项列表,遍历它们并将它们添加到我的 myObj.ProtectionOptions 属性中。我不知道如何在不使用按位或“|”的情况下循环执行此操作 操作员。这是我想做的事情:

string protectionOptionsString = "NoPrevention, PreventPrinting";
string[] protectionOptions = protectionOptionsString.Split(',');
foreach (string protectionOption in protectionOptions)
{
  myObj.Protection += (ProtectionOptions) Enum.Parse(typeof (ProtectionOptions), protectionOption.Trim());
}

从概念上讲,这就是我想要的,但我不能将循环中的值“+=”传递给参数。

4

4 回答 4

18

你不需要分开。如果您在枚举定义上使用 [Flags] 属性,则 Enum.Parse 能够解析多个值,您这样做了。只需解析并使用 |= 运算符来“添加”标志。

string protectionOptionsString = "NoPrevention, PreventPrinting";
myObj.Protection |= (ProtectionOptions)Enum.Parse(typeof(ProtectionOptions), protectionOptionsString);
于 2011-11-29T21:13:30.113 回答
4

使用|=运算符。

myObj.Protection |= (ProtectionOptions) Enum.Parse(typeof (ProtectionOptions), protectionOption.Trim());
于 2011-11-29T21:03:41.803 回答
1

Why can't you do this?

string protectionOptionsString = "NoPrevention, PreventPrinting";
string[] protectionOptions = protectionOptionsString.Split(',');
foreach (string protectionOption in protectionOptions)
{
  myObj.Protection |= (ProtectionOptions) Enum.Parse(typeof (ProtectionOptions), protectionOption.Trim());
}

Alternatively, you could store the integer equivalent of the enumeration ((Int32)myObj.Protection) and load it as an integer as well.

于 2011-11-29T21:04:37.050 回答
0

您想使用复合 OR 赋值运算符

string protectionOptionsString = "NoPrevention, PreventPrinting";
string[] protectionOptions = protectionOptionsString.Split(',');

foreach (string protectionOption in protectionOptions)
{
  myObj.Protection |= (ProtectionOptions)Enum.Parse(typeof(ProtectionOptions), 
                                                    protectionOption.Trim());
}
于 2011-11-29T21:03:24.923 回答