gpt4 book ai didi

c# - 将枚举标志附加到循环中的参数(按位附加)

转载 作者:行者123 更新时间:2023-11-30 13:09:09 25 4
gpt4 key购买 nike

在 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 属性中。我不知道如何在不使用按位或“|”的情况下循环执行此操作运算符(operator)。这是我想要做的:

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

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

最佳答案

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

string protectionOptionsString = "NoPrevention, PreventPrinting";
myObj.Protection |= (ProtectionOptions)Enum.Parse(typeof(ProtectionOptions), protectionOptionsString);

关于c# - 将枚举标志附加到循环中的参数(按位附加),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8317671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com