C# 将枚举标志追加到循环中的参数(按位追加)
在C#中,我试图向接受枚举标志的参数“添加”值。我可以用位运算符“|”在一行上完成,但我似乎不能在循环中附加到参数 我将以下枚举指定为标志C# 将枚举标志追加到循环中的参数(按位追加),c#,bit-manipulation,enum-flags,C#,Bit Manipulation,Enum Flags,在C#中,我试图向接受枚举标志的参数“添加”值。我可以用位运算符“|”在一行上完成,但我似乎不能在循环中附加到参数 我将以下枚举指定为标志 [Flags] public enum ProtectionOptions { NoPrevention = 0, PreventEverything = 1, PreventCopying = 2, PreventPrinting = 4, PrintOnlyLowResolution = 8 } 现在,我可以轻松地使用以下代码向参数
[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());
}
从概念上讲,这就是我想要的,但是我不能“+=”参数循环中的值。您想要使用
使用
|=
运算符
myObj.Protection |= (ProtectionOptions) Enum.Parse(typeof (ProtectionOptions), protectionOption.Trim());
你为什么不能这样做
string protectionOptionsString = "NoPrevention, PreventPrinting";
string[] protectionOptions = protectionOptionsString.Split(',');
foreach (string protectionOption in protectionOptions)
{
myObj.Protection |= (ProtectionOptions) Enum.Parse(typeof (ProtectionOptions), protectionOption.Trim());
}
或者,您可以存储枚举的整数等价物((Int32)myObj.Protection),并将其作为整数加载。您不需要拆分。如果您在枚举定义上使用[Flags]属性,则Parse能够解析多个值,您确实做到了这一点。只需解析并使用|=运算符“添加”标志
string protectionOptionsString = "NoPrevention, PreventPrinting";
myObj.Protection |= (ProtectionOptions)Enum.Parse(typeof(ProtectionOptions), protectionOptionsString);
完美的成功了。谢谢给你两个简短的问题。首先,出于好奇,如果我想在不使用内置解析函数的情况下“附加”标志,有可能吗?第二,对于我的枚举,我听到过关于是否应该使用0值并为其命名的相互矛盾的故事。如果我使用0值,它应该是“无”还是可以是任何值?如果值表示为字符串,则必须使用Parse转换为枚举实例。除非0为“无”,否则不应使用它。问题是,如果使用枚举的程序员检查值,他们有时会使用0进行比较(他们不应该这样做,但这很常见)。如果0是一个值,而不是缺少值,那么如果((currentWeather&Cloudy)!=0)要测试标志是否有Cloudy(当Cloudy定义为0时)将返回false,而不是预期的true。我在教程中详细提到了这一点。按照我在答案中指定的链接进行操作。谢谢塞尔达,这回答了我在莫蒂上发布的第一个问题。我接受了他的回答,因为它现在更适合我的需要,但这就清楚了,我需要使用“|=”而不是“+=”来附加。我很感激!
string protectionOptionsString = "NoPrevention, PreventPrinting";
myObj.Protection |= (ProtectionOptions)Enum.Parse(typeof(ProtectionOptions), protectionOptionsString);